Classes and objects in java

Let’s learn classes and objects in java.

Classes and objects in java

Class is a blueprint. Class is a collection of objects. To create a class in java use keyword ‘class’.

For example:

class Animal

Syntax:

access-modifier class ClassName
{
   // methods
   // constructors
}

In the below example I have created a class by name Employee. This class has variable salary of datatype integer.

public class Employee
{
   int salary = 50000;
}

Basically a class consists of intrinsic elements, namely

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


object definition

Object is an instance of a class. Object is a real world entity. Object occupies memory.

Object consists of identity, state or attribute and behaviour. Here’s realtime example of class and object.

classes and objects in java

Here’s how to create object in java with example.

There are three steps to create an object

  1. Declaration: For example, Bird sparrow;
  2. Instantiation: use “new” keyword, sparrow = new Bird();
  3. Initializaition: in initializaition use constructor.

Syntax for object creation:

Bird sparrow = new Bird();


multiple objects

Meanwhile we can create multiple objects of one class. For example.

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



Initialize an object in java

There are three ways to initialize an object in java.

  • by reference variable.
  • by method.
  • by constructor.

Let’s see an example to initialize an object in java – by reference variable.

import java.util.*;
class Employee
{
   String name;
   int age;
   public static void main(String[] args)
   {
      Employee emp = new Employee();
      emp.name = "Virat";
      emp.age = 23;
      System.out.println(emp.name + " " + emp.age);
   }
}


Output:

Virat 23


Here’s is an example to initialize an object in java by using method.

class Employee
{
   String empName;
   int empAge;
   void initialize(String name, int age)
   {
      empName = name;
      empAge = age;
   }
   void print()
   {
      System.out.println(empName + " " + empAge);
   }
   public static void main(String[] args)
   {
      Employee emp = new Employee();
      emp.initialize("virat", 23);
      emp.display();
   }
}


Output:

virat 23