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.

Syntax:

class ClassName
{
   // variables declaration
   // methods declaration
}


Class is a blueprint for creating 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.

Create a class

To create a class by name Employee use keyword ‘class’ and create variable salary of datatype integer,

NOTE: class name should start with uppercase first letter.

public class Employee
{
   int salary = 50000;
}


There are four types of classes in java, 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 and it is created from class. Object can be associated to real life. An object can have state, for example, a car can have model, color, etc.

Also read – variables in java

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

Create an object

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

class Employee
{
   int salary;
   public static void main(String[] args) 
   {
      Employee obj = new Employee();
      System.out.println(obj.salary);
   }
}



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

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

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

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

Creating multiple objects

Meanwhile we can create multiple objects of a class,

class Employee
{
   int salary;
   public static void main(String[] args) 
   {
      Employee obj1 = new Employee();
      Employee obj2 = new Emplyee();
      System.out.println(obj1.salary);
      System.out.println(obj2.salary);
   }
}



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 – java class constructor

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.