Classes and Objects in Java – Fundamentals of OOPs

As we learned in our previous lessons, Java is an object oriented programming language, In order to implement this concept, Java has features called as Classes and Objects in java. These are fundamental concepts in the field of Object Oriented Programming and having a good grasp of these concepts is essential for further concepts of OOP.

So, the big question is, what are classes and objects in java?

Classes & Objects in Java
Contrary to the popular definitions we all can search for on the internet, we take a detour and understand the concept with an example. Shall we?

Imagine you are God and you are assigned the task for creating and populating the earth with beings. So you use your magical powers and draw your first design of a human being. As soon as you think of the word Human, you immediately come to terms with the following points

1. The human has a head which thinks.
2. The human has two hands and two legs
3. The human has one torso to hold all his organs

What you created is just a blueprint of a human being. Notice that you didn’t create an actual human being yet but you managed to create a basic outline of what a human being must look like.

Upon further investigation and hours of meditation you come up with more concepts for your blueprint such as

4. The human has to have a name
5. The human has to either love tea or coffee or both.
And so on..

What you created till now is a blueprint of the word “Human”. In object oriented programming, this is ,in popular opinion, a class.

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Classes in Java

A class is the blueprint of all the objects that are derived from it. It represents the set of methods and properties that are common to all the objects which are referenced from it.

It has the methods, variables which are common to all the objects it projects onto.

A class declaration in Java has the following parts:

1. Modifier: This determines the accessibility of the class whether its public(accessible to all) or private(accessible to limited members of the program. )

2. Class name: This , as the name suggests, is the name of the class. It should not be any keyword. Convention suggests that all class names should begin with a capital letter.

3. Superclass(if any): Superclasses will be explained when we learn about inheritance in the later chapters. For now it is enough to know that superclasses are mentioned in the class declaration when it inherits data from a super class. The keyword used is “extends”.

4. Interface(if any): Interfaces are mentioned, separated by commas, individually after the class definition.

A sample Java class declaration is shown as follows:

class Person {
  int age;
  String name;
  char sex;
  Person(int age, String name) {
    this.age = age;
    this.name = name;
  }

  void speak() {
    System.out.println(“Hey my name is” + this.name + ”and I love learning from DataFlair”);
  }
  void run() {
    System.out.println(“Uh oh I am late
    for my class”);
  }
}

This is a basic example of a class.

However for clean code two classes can be created. One can hold all the methods and variables and the second class can hold the main method. Inside this main method the objects can be created of the first class.

Objects in Java

Remember when you were God and you created a blueprint called Person? . That blueprint was a class. But the world cannot run with the help of blueprints unless we reference them into an actual person.

Imagine the first people on earth, called Adam and Eve. They are the objects of the class Person. Though both of them share the same features they are different in many ways. They are Objects of the class Person.

The traditional definition of an object goes as follows:
“The objects are real life entities which are derived from classes.They share the same variables and methods but different values of them .”

Java Objects consists of:

1. State: The properties of an object is its state. Its reflected by the attributed possessed by the object

2. Behaviour: It is determined by the methods of the object. For example an object having a function to print (“Hello”) will be the behaviour of that particular object.

3. Identity: The name you allot to the object is its identity. It allows objects to interact with one another. Object names must be unique. Example- an object named as “Adam” references the person class.

Declaring Objects in Java

We are now familiar with the concept of objects. Its time we took to programming. Declaring objects is very easy to learn. Remember how we declared variables? Its the same here.
<type><object-name>.

For example if we want to declare an object named adam of the type Person. We would do so by the following way:

Person adam;

(Here you should note that the type of the object is the class. This illustrates the fact that classes are a non-primitive data type. )

It should always be a concrete class name. That’s why we can’t create objects of interfaces and classes.

Initialization of Java Object

Whenever an object is created, the class it references to is said to be instantiated. As soon as the object is initialized, all the instance variables are copied and reserved into memory for each individual object that is created.

Java also uses constructors which have the same name of the class for initializing or storing values of the instance variables. It depends on whether the constructor has parameters or not.

Whenever an object is declared using the ‘new’ keyword the constructor is called. Even if a constructor is not defined then a default constructor is called.

All of these concepts can be understood with the help of a simple Java Program.

Lets look at a full example of classes and objects altogether in Java.

import java.util. * ;
import java.io. * ;
class Person {
  String name;
  String sex;
  Person(String name, String sex) {
    this.name = name;
    this.sex = sex;
  }
  void print() {
    System.out.println("Hey my name is " + this.name + " I am " + this.sex);
  }
  public static void main(String[] args) throws IOException {
    Person adam = new Person("Adam", "Male"); //These values pass directly to the constructor. 
    Person eve = new Person("Eve", "Female"); //These values pass directly to the constructor. 
    adam.print();
    eve.print();
  }
}

Output:

Hey my name is Adam I am Male
Hey my name is Eve I am Female

Here as you can see the object is created in the main method. It has a name ‘adam’ and ‘eve’ for sake of understanding, but while completing your own programs you can have any name you want as long as it is not a reserved word.

There is also a parameterized constructor called Person(String name,String sex) which is fed values when the objects are created. However if there was no constructor defined Java would have a default constructor defined already. It either calls the parent class’s “no-argument” constructor or its object class constructor depending on whether it has a parent class or not.

Ways of Creating Object in Java

There are primarily 4 ways of creating objects.

1. New Keyword

This creates objects with the name mentioned. This is the most simple way to create objects in Java. This is the same type as the example we saw before.

2. Using the Class package

This is a slightly different method of declaring objects. There is a predefined class called Class in the java.lang package. This has a method called “forName” which takes one string argument “package.className”. The method returns an instance of the class of the same name as the string argument mentioned. This will be easier to understand with an example.

Consider the example above of a public class Person. Consider that its under a package name com.p1

So the code that will generate the object is:

Person adam = (Person)Class.forName(“com.p1.Person).newInstance();

As soon as this code is executed, an instance of the class Person is created with the name ‘adam’.  An object of name adam is created.

3. Using Clone method

As the name suggests, the clone method clones/copies all the variables and methods that are in an object into another object. It is a member of the Object class.

For Example:

Person adam= new Person();
Person adamclone = (Person)adam.clone();

This creates a clone of the object adam called adamclone

4. Deserialization in java

In order to understand this concept we first have to know what serialization and deserialization is.

The process of converting an object into a serial of bytes is called serialization.The reverse of this process is called deserialization.

The process of deserialization starts with reading the serialized file through the FileInputStream and passing the object to the ObjectOutputStream.

Java program to illustrate deserialization:

import java.io. * ;
class DeSerialize {
  public static void main(String[] args) throws IOException {
    try {

      FileInputStream fis = new FileInputStream("person.ser");
      ObjectOutPutStream ois = new ObjectOutputStrean("fis");
      pi = (personinfo) ois.readObject();
    }
    catch(Exception e) {
      e.printStackTrace();
      System.out.println("Name" + pi.name);
      System.out.println("I am" + pi.sex);
    }
  }
}

This program is actually executed when the person.ser is created and needs deserialization. Static variables are not serialized.

Accessing Instance Variables in Java

Instance variables can be accessed by using the dot(.) operator. The syntax is <object-name>.<variable-name>;

Java program to explain instance variable access:

import java.io. * ;
class InstanceVar {
  int x;
  InstanceVar() {
    x = 10;
  }
  public static void main(String[] args) throws IOException {
    InstanceVar ob = new InstanceVar();
    System.out.println("Instance Variable is" + ob.x);
  }
}

Output:

Instance Variable is 10

The value can also be changed by the same process.

However if you do not want it to be changed include the final keyword in the declaration of the instance variable.

Example:

class InstanceVar {
  final int x;
  InstanceVar() {
    x = 10;
  }
  public static void main(String[] args) throws IOException {
    InstanceVar ob = new InstanceVar();
    ob.x = 65; //Returns error
    System.out.println("Instance Variable is" + ob.x);
  }
}

Summary

Summing up, classes and objects in java are the preliminary concepts of Object Oriented Programming in Java and a good concept of classes is essential for future development. Classes come in handy when we need to develop datatypes of our own. So, it is important that we have a deep understanding of the topic before moving on.

1 Response

  1. shravan says:

    i read the java documents ant it completed providing the java feature with example.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.