MyClass.java
- public class MyClass {
- int myField;
- public MyClass(int value) {
- myField = value;
- }
- public static void main(String[] args) {
-
- MyClass myObject = new MyClass(10);
-
- System.out.println("Value of myField: " + myObject.myField);
- }
- }
Output:
Explanation
In this example, the constructor MyClass(int value) is called with the parameter 10, the reference to the newly constructed object is assigned to the variable myObject, and new MyClass(10) dynamically allocates memory for an object of type MyClass. Lastly, a printout of the instance variable myField's value is obtained.
Object and Class Example: main within the class
In Java, the main() method can be declared in a class, which is typically done in demonstration or basic programs. Having the main() method defined inside of a class allows a program to run immediately without creating a separate class containing it.
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
-
-
- class Student{
-
- int id;
- String name;
-
- public static void main(String args[]){
-
- Student s1=new Student();
-
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
Explanation
In this example, the constructor MyClass(int value) is invoked with the parameter 10, resulting in a new MyClass object being created and its reference assigned to the variable myObject. The new MyClass(10) statement dynamically allocates memory for this object. Finally, the value of the instance variable myField is printed.
Object and Class Example: main Method Within a Class
In Java, the main() method can be defined within a class, which is common for demonstrations or simple programs. This allows the program to run immediately without needing a separate class for execution.
In the following example, a Student class is created with two data members: id and name. We instantiate the Student class using the new keyword and print the object's values. The main() method is included within the class to facilitate running the program.
File: TestStudent1.java
-
-
-
- class Student{
- int id;
- String name;
- }
-
- class TestStudent1{
- public static void main(String args[]){
- Student s1=new Student();
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
Explanation
In this Java program, the main method is located in a different class than the Student class. The Student class does not define any methods for its fields, name and id. The main method exists in another class called TestStudent1, where it uses the default constructor to create an object s1 of type Student. Because the fields name and id are not explicitly initialized, they have default values: null for the String and 0 for the int.
Object Initialization in Java
There are three main ways to initialize an object in Java:
- By Reference Variable
- By Method
- By Constructor
1) Initialization through Reference Variable
Initializing an object means assigning data to its fields. Below is a simple example demonstrating how to initialize an object through a reference variable.
File: TestStudent2.java
- class Student{
- int id;
- String name;
- }
- class TestStudent2{
- public static void main(String args[]){
- Student s1=new Student();
- s1.id=101;
- s1.name="Sonoo";
- System.out.println(s1.id+" "+s1.name);
- }
- }
Output:
This Java code includes two classes: Student and TestStudent2. The Student class defines two fields, id and name, which represent the student's ID and name, respectively. The TestStudent2 class contains the main method, which serves as the entry point of the program. Inside this main method, an object s1 of type Student is created using the new keyword. The fields id and name of s1 are then initialized with the values 101 and "Sonoo".
Additionally, you can create multiple Student objects and store information in them using different reference variables.
File: TestStudent3.java- class Student{
- int id;
- String name;
- }
- class TestStudent3{
- public static void main(String args[]){
-
- Student s1=new Student();
- Student s2=new Student();
-
- s1.id=101;
- s1.name="Sonoo";
- s2.id=102;
- s2.name="Amit";
-
- System.out.println(s1.id+" "+s1.name);
- System.out.println(s2.id+" "+s2.name);
- }
- }
Output:
Explanation
This Java code illustrates how to create and initialize multiple Student class objects within the TestStudent3 class. Using the new keyword, two Student objects, s1 and s2, are created. Each object's id and name fields are then initialized separately: s1 has an id of 101 and a name of "Sonoo," while s2 is assigned an id of 102 and a name of "Amit."
2) Initialization via Method
In this example, we create two Student objects and initialize their values by calling the insertRecord method.
We display the state (data) of the objects by invoking the displayInformation() method.File: TestStudent4.java
- class Student{
- int rollno;
- String name;
- void insertRecord(int r, String n){
- rollno=r;
- name=n;
- }
- void displayInformation(){System.out.println(rollno+" "+name);}
- }
- class TestStudent4{
- public static void main(String args[]){
- Student s1=new Student();
- Student s2=new Student();
- s1.insertRecord(111,"Karan");
- s2.insertRecord(222,"Aryan");
- s1.displayInformation();
- s2.displayInformation();
- }
- }
Output:
11 Karan
222 Aryan
The Java code provided defines two classes: Student and TestStudent4. The Student class contains fields for rollno and name, along with methods insertRecord and displayInformation to initialize and display the respective data. In the main method of the TestStudent4 class, two Student objects are created, and their insertRecord methods are called to set the values for rollno and name.

As illustrated in the figure above, objects are stored in the heap memory area, and reference variables point to these objects in memory. In this context, s1 and s2 are reference variables that reference the objects allocated in the heap.
3) Initialization Using a Constructor
Object initialization through a constructor is a fundamental concept in object-oriented programming in Java. Constructors are special methods within a class that are invoked when an object of that class is created using the new keyword. They set up the object's state by providing initial values for its fields or performing necessary setup tasks. The constructor is automatically called upon instantiating an object, ensuring that the object is properly initialized before it is used.
Here’s an example that demonstrates object initialization via a constructor:
File: ObjectConstructor.java- class Student {
- int id;
- String name;
-
- public Student(int id, String name) {
- this.id = id;
- this.name = name;
- }
-
- public void displayInformation() {
- System.out.println("Student ID: " + id);
- System.out.println("Student Name: " + name);
- }
- }
- public class ObjectConstructor {
- public static void main(String[] args) {
-
- Student student1 = new Student(1, "John Doe");
- Student student2 = new Student(2, "Jane Smith");
-
- student1.displayInformation();
- student2.displayInformation();
- }
- }
Output:
Student ID: 1
Student Name: John Doe
Student ID: 2
Student Name: Jane Smith
Explanation
In this example, the id and name fields of a Student object are initialized through a constructor defined in the Student class, which takes two parameters: id and name. When creating the student1 and student2 objects using this constructor, their fields are set with the provided values. This approach ensures that objects are created with the correct initial values, making it simpler to instantiate and use them later in the program.
Object and Class Example: Employee
Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
- class Employee{
- int id;
- String name;
- float salary;
- void insert(int i, String n, float s) {
- id=i;
- name=n;
- salary=s;
- }
- void display(){System.out.println(id+" "+name+" "+salary);}
- }
- public class TestEmployee {
- public static void main(String[] args) {
- Employee e1=new Employee();
- Employee e2=new Employee();
- Employee e3=new Employee();
- e1.insert(101,"ajeet",45000);
- e2.insert(102,"irfan",25000);
- e3.insert(103,"nakul",55000);
- e1.display();
- e2.display();
- e3.display();
- }
- }
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
Explanation
The Employee class in this Java code defines three fields: id, name, and salary. It includes two methods: insert, which sets the values of the fields, and display, which prints those values. In the main function of the TestEmployee class, three Employee objects (e1, e2, and e3) are created. The insert method is called for each object to initialize the id, name, and salary fields with specific values. Subsequently, the display method is invoked for each object to show the initialized data.
Object and Class Example: Rectangle
Another example is provided that handles the records for a Rectangle class.File: TestRectangle1.java
- class Rectangle{
- int length;
- int width;
- void insert(int l, int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- }
- class TestRectangle1{
- public static void main(String args[]){
- Rectangle r1=new Rectangle();
- Rectangle r2=new Rectangle();
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
Explanation
This Java code defines a Rectangle class with fields for length and width, along with methods to set the dimensions and calculate the area. In the main method of the TestRectangle1 class, two Rectangle objects are created, and their dimensions are set using the insert method.
Different Ways to Create an Object in Java
Using the new Keyword
The most common way to create an object in Java is with the new keyword followed by a constructor.
Example:java
ClassName obj = new ClassName();
This allocates memory for the object and calls its constructor to initialize it.
Using the newInstance() Method
This method, part of the java.lang.Class class, creates a new instance of a class dynamically at runtime, invoking the no-argument constructor.
Example:java
ClassName obj = (ClassName) Class.forName("ClassName").newInstance();
Using the clone() Method
The clone() method creates a copy of an existing object through a shallow copy, returning a new object that duplicates the original.
Example:java
ClassName obj2 = (ClassName) obj1.clone();
Using Deserialization
Objects can be created by deserializing them from a stream of bytes using the ObjectInputStream class. The object is read from a file or network, and the readObject() method is called to recreate it.
Using Factory Methods
Factory methods are static methods within a class that return instances of that class. They allow for encapsulating the object creation logic without directly invoking a constructor.
Example:java
ClassName obj = ClassName.createInstance();
These methods provide flexibility in how objects are instantiated in Java, catering to different needs and scenarios.
We will learn these ways to create object later.
Anonymous Object
An anonymous object is one that does not have a name or reference. It can only be used at the time of its creation.
Calling method through a reference:
- Calculation c=new Calculation();
- c.fact(5);
Calling method through an anonymous object
- new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
- class Calculation{
- void fact(int n){
- int fact=1;
- for(int i=1;i<=n;i++){
- fact=fact*i;
- }
- System.out.println("factorial is "+fact);
- }
- public static void main(String args[]){
- new Calculation().fact(5);
- }
- }
Output:
Explanation
The factorial of an integer \( n \) can be calculated using Java code that defines a `Calculation` class with a `factorial` method. This method employs a for loop to compute the factorial by iterating from 1 to \( n \), and the result is then printed to the console. The main method demonstrates the use of an anonymous `Calculation` class object, which calls the `factorial` method with the parameter 5, showcasing how to use anonymous objects in Java for one-time method invocations.
Creating Multiple Objects of One Type
In Java, it's possible to create multiple objects of the same type, similar to how we handle primitive data types.
Initialization of Primitive Variables
Initialization of Reference Variables
- Rectangle r1=new Rectangle(), r2=new Rectangle();
Let's see the example:
-
-
- class Rectangle{
- int length;
- int width;
- void insert(int l,int w){
- length=l;
- width=w;
- }
- void calculateArea(){System.out.println(length*width);}
- }
- class TestRectangle2{
- public static void main(String args[]){
- Rectangle r1=new Rectangle(),r2=new Rectangle();
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
Explanation
This Java program demonstrates the use of a Rectangle class, which has length and width as its data members. The class includes methods to insert dimensions and compute the area of a rectangle. In the main method of the TestRectangle2 class, two Rectangle objects (r1 and r2) are created in a single line using a comma-separated list, showcasing the ability to instantiate multiple objects of the same type at once. Each object's dimensions are set by calling the insert method, and the area of each rectangle is calculated and printed using the calculateArea method.
Real World Example: Account
File: TestAccount.java
-
-
-
- class Account{
- int acc_no;
- String name;
- float amount;
-
- void insert(int a,String n,float amt){
- acc_no=a;
- name=n;
- amount=amt;
- }
-
- void deposit(float amt){
- amount=amount+amt;
- System.out.println(amt+" deposited");
- }
-
- void withdraw(float amt){
- if(amount<amt){
- System.out.println("Insufficient Balance");
- }else{
- amount=amount-amt;
- System.out.println(amt+" withdrawn");
- }
- }
-
- void checkBalance(){System.out.println("Balance is: "+amount);}
-
- void display(){System.out.println(acc_no+" "+name+" "+amount);}
- }
-
- class TestAccount{
- public static void main(String[] args){
- Account a1=new Account();
- a1.insert(832345,"Ankit",1000);
- a1.display();
- a1.checkBalance();
- a1.deposit(40000);
- a1.checkBalance();
- a1.withdraw(15000);
- a1.checkBalance();
- }}
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0
Explanation
The Account class in this Java program simulates a basic banking system with features for depositing, withdrawing, checking the balance, and viewing account details. It includes attributes such as account number, account holder's name, and balance amount. The main method of the TestAccount class is responsible for creating and initializing an Account object, a1, with the relevant information. Afterward, the account is utilized for deposits and withdrawals, and the balance is checked after each transaction.