Classes and Objects in Java With Examples

In this post, we will deal with the Java Classes and Objects. Java is an object-oriented programming language so classes and objects are used to design a program. An object can be both physical and logical entity but class is only a logical entity.

Classes and Objects in Java

Object in Java

An object is any type of physical and logical entity that has state and behaviors. It can be both tangible and intangible. An object has an address and occupies memory. They can communicate without the knowledge of data or code of each other.

Objects in Java

The major characteristics of an object are:

  • State: It indicates the value of an object. It is represented through attributes and reflects the features of an object.
  • Behavior: It indicates the functionality of an object. It is represented through methods and reflects the response of an object with other objects.
  • Identity: Identity is the unique way to identify each object. The identity of an object is not always seen by the external user and it is implemented through a different ID. It refers to the unique name of the object that differentiates it from other objects and helps in the interaction between objects.

Objects are an instance of a class. A class is a logical entity which has more than one object and they are the blueprints which are used to make a single object.

Some other definitions of an object are:

  • An object can be defined as a real-world entity.
  • An object can be defined as a runtime entity.
  • An object has state and behaviors.
  • Objects are an instance of a class.

Class in Java

A class is a logical entity which has more than one object with common characteristics. They are the blueprints which are used to make a single object and don’t take up any space. The features or methods that are common in a type of objects are represented by a class.

Public class Car {
    // methods & fields...
}

A class in Java contains:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

Example of a class and object :

1. Car.java

public class Car {

	String brand;
	String color;
	int price;
}

2. CarTest.java

public class CarTest {

	public static void main(String[] args) {

		Car car = new Car();

		car.brand = "BMW";
		car.color = "red";
		car.price = 40000;

		System.out.println("Car brand: " + car.brand + ", Car color: " + car.color + ", Car Price: " + car.price);

	}

}

Instance variable in Java

An instance variable is such type of variable which is created inside a class but outside a method. They don’t consume any memory at compile time and only consumes memory when at runtime. As it only gets memory when an instance is created, it is called an instance variable.

public class Car {

	String brand; // <-- instance variable 
	String color; // <-- instance variable 
	int price;   // <-- instance variable 

}

Method in Java

A method in Java is like a function. It is used to define the behavior of an object. For example :

public class CarTest {

	static void carRun() {
		System.out.println("Car is running");
	}

	public static void main(String[] args) {

		carRun();

		// output --> Car is running
	}
}

 

Advantage of method

  • Optimization of code.
  • Reuse of code.

New Keyword in Java

The new keyword is used in Java for allocation of memory during the runtime. All objects consume memory in the Heap memory area.

Ways to initialize an object

  • Through the reference variable.
  • Through method.
  • Through constructor.

Ways to create an object in Java

Some of the ways to create an object in Java are:

  • Through new keyword.
  • Through new instance method.
  • Through clone method.
  • Through deserialization.
  • Through factory method.

Anonymous object

The simple meaning of anonymous is nameless. An anonymous object is an object without any reference. It is only used when an object is created and the object is only going to be used once.

Constructor in Java

A constructor in Java is defined as a block of codes. It is similar to a method and is called when an instance of an object is created and allocation of memory for the object is done. It is used to initialize the object.

public class Car {

	private String brand;
	private String color;
	private double price;

	public Car() { // Constructor
	}
	public Car(String brand) { // Constructor
	}
	public Car(String brand, String color, double price) { // Constructor
	}
}

When is a constructor called?

A constructor is called each time a new keyword is used to create an object. It is also known as default constructor. Its main objective is to construct the value when an object is created so it is called the constructor.

Java compiler automatically creates a default constructor for a class if it does not have any so it is not compulsory to create a constructor for a class.

Rules for creating Java constructor

The two rules to follow while defining a constructor and they are:

  1. The name of the constructor must be the same as the class name.
  2. A constructor should not have an explicit return type.

Type of Java constructors

The two types of constructors in Java are:

  1. Default or No-arg constructor
  2. Parameterized constructor

Java Default Constructor

A default constructor is such type of constructor that doesn’t have any parameter. The main function of the default constructor is to assign default values to objects like 0, null, etc. on the basis of the type.

Java Parameterized constructor

A parameterized constructor is a constructor with a specific number of parameters. It is used to provide separate values to the different objects.

Constructor overloading in Java

A constructor is like a method in Java, the only difference is it does not have a return type. So it can be overloaded like a method as well. Constructor overloading in Java is the process if creating more than a single constructor but with various parameter lists.

Each of the constructors is arranged in such a way so that each of them carries out different tasks. The different constructors are separated by the compiler on the basis of the number and the types of parameters in their list.

Here is an example:

public class Car {

	public Car() {
	}
	public Car(String brand) {
	}
	public Car(double price) {

	}
}

Difference between a constructor and a method in Java

Several differences can be found between a constructor and a method. Some of them are:

  1. A constructor is mainly used to initialize the state of an object, whereas the main function of a method is to expose the behavior of an object.
  2. A constructor should not have return type but a method should.
  3. A constructor is invoked implicitly but a method is invoked explicitly.
  4. A default constructor is provided if there is not any by the Java compiler, whereas a method is not ever provided by the compiler.
  5. A constructor name is always the same as the class name but a method name may or may not be similar to the class name.

Leave a Reply

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