In this tutorial, we will learn object declaration and initialization in Java with the help of examples. We will learn different ways to initialize value or data of the state of an object inside a class.
We will cover the following topics:
- Object declaration in Java
- Object initialization in Java
- Ways to initialize states of an object in Java
So, let us understand each topic one by one.
Object Declaration in Java
The process of defining a reference variable of a class type is called object declaration in Java. The general syntax to declare a reference object of class type is as:
ClassName objectName;Example: Object Declaration
College c;
In this example:
- College is the name of the class, and c is the reference variable.
- At this stage, no object is created.
- Only memory for the reference variable is allocated, and it refers to no object. It contains null by default.
Object Initialization in Java
The process of assigning initial values to the instance variables of an object is called object initialization in Java. These initial values represent the state of an object. We can also define object initialization as:
Object initialization is the process of storing initial data into the instance variables of an object so that the object can represent meaningful information.
Example: Direct Object Initialization
class College
{
// Initialize the value of variables.
String name = "PIET";
String city = "Nagpur";
}In this example, the instance variables name and city are initialized with the values “PIET” and “Nagpur” respectively. This type of initialization is called direct initialization of instance variables. When we will create an object of class College, these values are automatically assigned.
Ways to Initialize an Object in Java
In Java, there are four standard ways by which we can initialize the state of an object. In other words, we can initialize the value of variables in Java by using four ways. They are:
- Initialize object using constructor
- Initialize object using reference variable
- Initialize object using method
- Initialize object using instance block
Let us understand each way with syntax and example one by one.
Object Initialization Using Constructor
Constructor is the best and most recommended way to initialize objects in modern Java. A constructor in Java is a special member of a class that is used to initialize objects of class. It is automatically called when an object of the class is created. The constructor initializes the instance variables of the object.
A constructor does not have any return type, not even void. If the return type is specified, the JVM considers it as a normal method, not a constructor.
Syntax to Initialize Object Using Constructor
ClassName(parameters)
{
variableName = value;
}Let’s take an example program in which we will store data into an object using a constructor.
Example:
package objectPrograms;
public class Student
{
// Declaration of instance variables (states of an object).
String name;
int rollNo;
int age;
// Declaration of a no-argument constructor.
// The constructor name must be the same as the class name.
Student()
{
// Initialize states of an object (values of instance variables).
name = "Saanvi";
rollNo = 5;
age = 15;
}
// Declare an instance method.
void display()
{
// Display the values of instance variables.
// This is an instance area. Therefore, we can directly access the instance variables.
System.out.println("Student's name: " +name);
System.out.println("Student's roll no: " +rollNo);
System.out.println("Student's age: " +age);
}
// Declare the main method. It is a static method. So, it is a static area.
public static void main(String[] args) {
// Create an object of the class.
Student st = new Student(); // It will automatically call the no-argument constructor.
// Call the instance method using object reference variable st.
// Because we cannot call non-static members directly in the static region.
st.display();
}
}Output:
Student's name: Saanvi Student's roll no: 5 Student's age: 15
Object Initialization Using Reference Variable
This is the simplest and most commonly used method to initialize the states of an object. In this method, we assign values to the instance variables using object reference variable.
The general syntax to initialize values to instance variables using object reference is:
objectName.variableName = value;Let’s take an example program where we will assign values to instance variables using an object reference variable.
Example 2:
package objectPrograms;
public class Marks
{
// Declare instance variables.
String subject1;
int sub1Marks;
String subject2;
int sub2Marks;
// Declare main method.
public static void main(String[] args)
{
// Create an object of the class.
Marks mk = new Marks();
// Initialize values of variables using object reference variable and dot notation.
mk.subject1 = "Science";
mk.sub1Marks = 90;
mk.subject2 = "Maths";
mk.sub2Marks = 99;
// Adding total marks and storing into a variable named totalMarks.
int totalMarks = 90 + 99;
// Call marks using object reference variable.
System.out.println("Marks in Science:" +mk.sub1Marks);
System.out.println("Marks in Maths:" +mk.sub2Marks);
System.out.println("Total Marks: " +totalMarks);
}
}
Output:
Marks in Science: 90 Marks in Maths: 99 Total Marks: 189
In this example:
- We have created a class named “Marks”.
- Then, we have declared four instance variables.
- Inside the main method, we have called instance variables using object reference variable “mk” and initialized them with values.
Object Initialization Using Method
This is the third standard way to initialize objects in Java. In this method, we assign values to the instance variables through a method.
A method in Java is a set of code that contains statements to perform a specific task or operation. It helps in organizing and reusing the code. When a method is called, it may return a value to the caller. However, it does not return a value if its return type is void.
Let’s take an example program in which we will assign values to the instance variables using method.
Example 3:
package objectPrograms;
public class Rectangle
{
int length;
int breadth;
// Declare an instance method with parameters l and b of data type int.
void perValue(int l, int b)
{
// Here, we are setting the name of parameters different from the name of the variables.
// Because we are not using this reference.
length = l;
breadth = b;
}
void calculate()
{
int perimeter = 2 * (length + breadth);
System.out.println("Perimeter of rectangle: " +perimeter);
}
public static void main(String[] args)
{
// Create the first object of class.
Rectangle rt = new Rectangle();
// This statement will call perValue method and initialize values to the instance variables.
rt.perValue(20, 30);
// This statement will call calculate() method and display the output.
rt.calculate();
// Create the another object of class.
Rectangle rt2 = new Rectangle();
rt2.perValue(50, 50);
rt2.calculate();
}
}
Output:
Perimeter of rectangle: 100 Perimeter of rectangle: 200
In this example, we have created two objects of the Rectangle class and initialize values to these objects by calling perValue() method.
Initialize Object Using Instance Initializer Block
In this method, we use instance initializer block to assign values to instance variables. Instance initializer block is executed automatically before constructor when we create an object of the class. The general syntax to declare instance initializer block in Java is:
{
// initialization code
}Let us take an example in which we will initialize instance variables inside the instance block.
Example 4:
package squareProgram;
public class Square
{
// Declare an instance variable.
int side;
// Declare an instance initializer block.
{
side = 45; // Initialization of an instance variable.
}
void calArea()
{
int area = side * side;
System.out.println("Area: " +area);
}
void calPerimeter()
{
int perimeter = 4 * side;
System.out.println("Perimeter: " +perimeter);
}
public static void main(String[] args)
{
// Creating an object of class Square.
Square sq = new Square();
// Calling methods using object reference.
sq.calArea();
sq.calPerimeter();
}
}Output:
Area: 2025 Perimeter: 180
In this example, we have declared an instance initializer block to assign value to the instance variable side. Then, we have defined two instance methods named calArea() and calArea() where we have written logic for calculation of area and perimeter.
Comparison Table for Object Initialization in Java
| Method | Recommended | Usage |
|---|---|---|
| Reference variable | Yes | Simple programs |
| Method | Yes | Flexible initialization |
| Constructor | Most recommended | Professional and real-world use |
| Initializer block | Rarely used | Special cases |
Key Points of Object Declaration and Initialization in Java
Following are key points for object declaration and initialization in Java that you should keep in mind:
- Declaring a reference variable of a class is called object declaration.
- Assigning values to instance variables of an object is called object initialization.
- An object can be initialized in four ways:
- Using reference variable
- Using method
- Using constructor
- Using instance initializer block
