Objects and Classes in Java
What is an object in Java?

Characteristics of an Object
- An object is a real-world entity.
- An object is a runtime entity.
- An object is an entity that has state and behavior.
- An object is an instance of a class.
What is a Class in Java?
A class in Java can contain
:
1. Fields
2. Methods
Methods are functions defined within a class that describe the actions or behaviors that objects of that class can perform. They enable interaction with and modification of an object's state (its fields). Methods can either be void (returning nothing) or return values, and they can also have different access modifiers.
- class <class_name>{
- field;
- method;
- }
Instance Variable in Java
Code Reusability: Methods promote code reusability by allowing the same block of code to be executed multiple times throughout a program. Once defined, a method can be called from anywhere within its scope.
Code Optimization: Methods help optimize code by encapsulating complex or repetitive tasks into reusable components. This modularization enhances readability and simplifies maintenance.
The new Keyword in Java
MyClass.java
- public class MyClass {
- int myField;
- public MyClass(int value) {
- myField = value;
- }
- public static void main(String[] args) {
- // Using the new keyword to create an instance of MyClass
- MyClass myObject = new MyClass(10);
- // Accessing the instance variable of the object
- System.out.println("Value of myField: " + myObject.myField);
- }
- }
Output:
Value of myField: 10
- //Java Program to illustrate how to define a class and fields
- //Defining a Student class.
- class Student{
- //defining fields
- int id;//field or data member or instance variable
- String name;
- //creating main method inside the Student class
- public static void main(String args[]){
- //Creating an object or instance
- Student s1=new Student();//creating an object of Student
- //Printing values of the object
- System.out.println(s1.id);//accessing member through reference variable
- System.out.println(s1.name);
- }
- }
Output:
0 null
Explanation
File: TestStudent1.java
- //Java Program to demonstrate having the main method in
- //another class
- //Creating Student class.
- class Student{
- int id;
- String name;
- }
- //Creating another class TestStudent1 which contains the main method
- class TestStudent1{
- public static void main(String args[]){
- Student s1=new Student();
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
Output:
0 null
Explanation
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);//printing members with a white space
- }
- }
Output:
101 Sonoo
- class Student{
- int id;
- String name;
- }
- class TestStudent3{
- public static void main(String args[]){
- //Creating objects
- Student s1=new Student();
- Student s2=new Student();
- //Initializing objects
- s1.id=101;
- s1.name="Sonoo";
- s2.id=102;
- s2.name="Amit";
- //Printing data
- System.out.println(s1.id+" "+s1.name);
- System.out.println(s2.id+" "+s2.name);
- }
- }
Output:
101 Sonoo 102 Amit
Explanation
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
Explanation
- class Student {
- int id;
- String name;
- // Constructor with parameters
- public Student(int id, String name) {
- this.id = id;
- this.name = name;
- }
- // Method to display student information
- public void displayInformation() {
- System.out.println("Student ID: " + id);
- System.out.println("Student Name: " + name);
- }
- }
- public class ObjectConstructor {
- public static void main(String[] args) {
- // Creating objects of Student class with constructor
- Student student1 = new Student(1, "John Doe");
- Student student2 = new Student(2, "Jane Smith");
- // Displaying information of the objects
- student1.displayInformation();
- student2.displayInformation();
- }
- }
Output:
Student ID: 1 Student Name: John Doe Student ID: 2 Student Name: Jane Smith
Explanation
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
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:
55 45
Explanation

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);//calling method with anonymous object
- }
- }
Output:
Factorial is 120
- int a=10, b=20;
Initialization of Reference Variables
- Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
Let's see the example:
- //Java Program to illustrate the use of Rectangle class which
- //has length and width data members
- 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();//creating two objects
- r1.insert(11,5);
- r2.insert(3,15);
- r1.calculateArea();
- r2.calculateArea();
- }
- }
Output:
55 45
Explanation
Real World Example: Account
File: TestAccount.java
- //Java Program to demonstrate the working of a banking-system
- //where we deposit and withdraw amount from our account.
- //Creating an Account class which has deposit() and withdraw() methods
- class Account{
- int acc_no;
- String name;
- float amount;
- //Method to initialize object
- void insert(int a,String n,float amt){
- acc_no=a;
- name=n;
- amount=amt;
- }
- //deposit method
- void deposit(float amt){
- amount=amount+amt;
- System.out.println(amt+" deposited");
- }
- //withdraw method
- void withdraw(float amt){
- if(amount<amt){
- System.out.println("Insufficient Balance");
- }else{
- amount=amount-amt;
- System.out.println(amt+" withdrawn");
- }
- }
- //method to check the balance of the account
- void checkBalance(){System.out.println("Balance is: "+amount);}
- //method to display the values of an object
- void display(){System.out.println(acc_no+" "+name+" "+amount);}
- }
- //Creating a test class to deposit and withdraw 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