Classes and objects in java

Let’s learn classes and objects in java.

Classes and objects in java

A class is a data structure where you can define variables called member variables and methods called member methods.

Class is a blueprint and has got an important property, that is, you can create an object from class.

Object represent properties of a class which is common for all objects. Every java program has at least one class and one main method.

There are four types of classes, namely, local, inner, nested and anonymous class.

Refer – nested class in java

Basically a class contain intrinsic elements namely,

Another important element of a class is constructor. Constructor is used to initialize objects.


What is an object?

Object is an instance of a class. It can be associated to real life object. An object can have state, for example, a car can have model, color, etc.

An object can have behaviour. For example car engine on, accelerates, stops etc.

Also object identity is distinct. Object name should be unique which enables in interacting with other objects. For example: Audi.

classes and objects in java

Declaring objects

To create an object we need a class. For example,

class Employee
{
   int id;
   public void display()
   {
      System.out.println("Hello World");
   }
}



Above class “Employee” has one variable and method. Now let’s instantiate class Employee,

Employee john = new Employee(); // Employee() is constructor

Now class Employee is instantiated after creating object “john”. This instance “john” share attributes and behaviour of class Employee.

NOTE: value of attributes are unique for object “john”.


Initializing an object

To initialize an object, constructor is used. “new” keyword instantiates class by assigning heap memory for object and returns reference to that memory.

// class employee can have "n" number of instances
class Employee
{ 
   int id;
   String name;
   int age;
}

public class ObjectDemo
{
   public static void main(String[] args)
   {
      // class is instantiated
      Employee john = new Employee(); // john is an object or an instance
      // "john" object share all the attributes 
      // and behaviour of class "Employee"
      john.id = 05;
      john.name = "John Thames";
      john.age = 14;
      System.out.println(john.name + " is " + john.age + " years old.");
      Employee sam = new Employee(); // sam is object or instance
      sam.id = 06;
      sam.name = "Sam joseph";
      sam.age = 15;
      System.out.println(sam.name + " is " + sam.age + " years old.");
   }
}



We have created class “Employee”. Class “Employee” has variable “id” of type integer, employee “name” of type string and employee “age” of type integer.

Also read – static keyword in java

Now to call class “Employee” in main method we have to create an instance of class Employee.

So, to do that give a name to its instance, john. We have created an instance of class “Employee”.

Now this instance is used to assign values to the member variables of class “Employee” as shown above.

In similar way we can create different instances of class “Employee”. So using a class we can define object which are independent of each other.

So in the above example “john” instance values are independent of “sam” instance values.

This is very important property of object that it can store its own state and it’s independent of other instance.

Now in java programming direct usage of variables is discouraged.

john.id = 05;

john.name = “John Thames”;

john.age = 14;

Because any programmer can modify these values. So we use getter and setter methods. Here’s the code,

class Employee
{
   int id;
   String name;
   int age;
   
   // constructor    
   Employee(int id, String name, int age)
   {
      this.id = id;
      this.name = name;
      this.age = age;
   }
 
   public int getId()
   {
      return id;
   }

   public void setId(int id)
   {
      this.id = id;
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }

   @Override
   public String toString() 
   { 
       return("Employee name is " + this.getName() + " his age is " + this.getAge() + " and ID " + this.getId());
   }
}



So, to assign value to variable “id” we use “setId” method and to get value of “id” we use “getId” method and this is called encapsulation of a variable.

read more about – constructor in java

This is important because we do not want to give access to variables to other users. Now to assign value to “john” and “sam” instance we use below format,

public class SampleExample
{
   public static void main(String[] args)
   {
      Employee john = new Employee(452, "John Thames", 23);
      System.out.println(john.toString());
      Employee sam = new Employee(453, "Sam joseph", 29);
      System.out.println(sam.toString());
   }
}



Output:

Employee name is John Thames his age is 23 and ID 452
Employee name is Sam joseph his age is 29 and ID 453

This way is more preferred when you are accessing or assigning values to member variables.


Various ways to instantiate object in java

There are different ways to instantiate an object. Below are few,

  1. New keyword: we just saw a program using new keyword.

      2. class.forName and new instance: here Class is predefined in package java.lang. “forName” is static method in “Class” which returns the Class object associated with the class or interface with the given string name.

Employee emp = (Employee)Class.forName(com.flowerbrackets.Employee).newInstance;

// newInstance() creates object of the class and return object.

    3. Using deserialization: deserialization is reading back serialized version of objects.

// serializing object to file and initializing with "dhoni"
Employee emp = new Employee("Dhoni");
// storing object in file "Employee.txt"
FileOutputStream file = new FileOutputStream("Employee.txt");
// creating ObjectOutputStream with "file" variable as input
ObjectOutputStream obj = new ObjectOutputStream(file);
// emp gets serialized and stored in "Employee.txt" 
obj.writeObject(emp);
obj.flush();

// deserializing
FileInputStream in = new FileInputStream("Employee.txt");
// opposite of ObjectOutputStream
ObjectInputStream obj1 = new ObjectInputStream(in);
// converting into object and type casting to Employee
Employee emp1 = (Employee)obj1.readObject();
obj1.close();



4. Anonymous object – is one which does not have name. Anonymous object consume memory only in heap memory. For example,

class Student
{
   int studentID;

   public void display()
   {
      System.out.println("Hello world");
   }
}

public class StudentDemo 
{
   public static void main(String[] args) 
   {
      // anonymous object
      new Student().display();
   }
}



Output:

Hello world

Advantages:

  • anonymous object does not use memory in stack.
  • when you want to use an object only once, use anonymous object.