Java Classes And Objects

Classes and objects are fundamental components in object-oriented programming, serving as essential elements in the structure of OOP (Object-Oriented Programming). Java programming heavily relies on the utilization of classes and objects, making them indispensable for program creation. The following section will delve into a comprehensive exploration of classes and objects in the context of Java programming.

What is a Class in Java?

A class represents a collection of objects sharing similar characteristics, serving as a model or plan for creating instances. It is a conceptual unit, devoid of physical form.

A Java class contains:

1. Fields

Fields within a class that represent the state of instances created from the class are known as fields or instance variables. These variables define the information that will be held within each instance of the class. Access modifiers like public, private, and protected can be utilized to control the accessibility and usage of these fields.

2. Methods

Methods are essentially functions that are encapsulated within a class and describe the operations or functionalities that instances of that class can execute. These functions serve as the interface through which external entities can interact with and modify the properties (attributes) of the object. Furthermore, methods can be of void type, meaning they do not return any value, or they can have various access specifiers. They are also capable of returning data outputs.

3. Constructors

Constructors serve as special functions responsible for initializing instances of a class. They are invoked when a new object is instantiated using the new keyword, bearing the identical name as the class itself. These methods are utilized to set initial values to object fields or execute any necessary setup operations during object creation.

4. Blocks

In Java classes, there are two types of blocks: instance blocks, known as initialization blocks, and static blocks. Static blocks, primarily utilized for static initialization, run just once when the class is loaded into memory. Instance blocks are employed to initialize instance variables and run every time a class object is created.

5. Nested Class and Interface

In Java, it is possible to nest classes and interfaces within other classes and interfaces. Nested classes, whether static or non-static, can access the members (fields, methods) of the enclosing class. Nested interfaces, being implicitly static, are useful for organizing related constants and methods in a logical manner.

Java Class Syntax

Example

class <class_name>{

    field;

    method;

}

What is an object in Java?

A physical object represents a real-life entity that possesses characteristics and actions. Put simply, an object is a concrete item that is tangible and can be interacted with physically, such as a vehicle or furniture. On the contrary, a conceptual object like the banking system lacks a physical form. Each object is uniquely identifiable, typically through a special identifier that the Java Virtual Machine (JVM) employs for recognition purposes.

Characteristics of an Object

  • State: It represents the data (value) of an object.
  • Behavior: It represents the behavior (functionality) of an object, such as deposit, withdraw, etc.
  • Identity: An object's identity is typically implemented via a unique ID. The ID's value is not visible to the external user; however, it is internally used by the JVM to identify each object uniquely.

An illustration can be seen in a pen, which is an item known as Reynolds, with a white hue that represents its state, primarily utilized for writing, which characterizes its function.

An object represents a specific occurrence of a class, which serves as a model or plan for creating objects. In essence, an object is a concrete realization of a class.

Object Definitions

  • An object is a real-world entity .
  • An object is a runtime entity .
  • The object is an entity that has state and behavior.
  • The object is an instance of a class .
  • Syntax of an Object

    Example
    
    <class_name> variable=new <class_name>();
    

    new keyword in Java

The "new" keyword is employed for dynamic memory allocation during program execution. Objects are allocated memory in the Heap memory region.

In Java, when creating an instance of a class (referred to as an object), the new keyword is used. This keyword allocates memory dynamically for an object of the class and provides a reference to it when coupled with the class name and optional arguments enclosed in brackets.

To read more Java new keyword

Class Example: main Method Within The Class

In Java, it is common practice to define the main method within a class, especially in simple or introductory programs. By including the main method within a class, the program can execute directly without the need for an additional class to hold it.

In this instance, we've established a Main class with two attributes, namely id and name. An instance of the Main class is then instantiated using the new keyword, followed by the printing of the object's value.

Example

Example

//Java Program to illustrate how to define a class and fields  

//Defining a Student class.  

class Main{  

 //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  

  Main s1=new Main();//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:

Output

0 

null

Explanation

The Java program includes two attributes in the Main class: an integer variable for the id and a string variable for the name. Within the Main class, the main method is defined as the primary entry point. Inside the main method, an object named s1 of the Main class is instantiated using the new keyword. Since the attributes are not initialized explicitly, they retain their default values of 0 for the integer type and null for the string type, which are then displayed. Lastly, the program outputs the values stored in the name and id attributes of the s1 object.

Class Example: main Method Outside The Class

In practical software development, it is common to structure Java classes into separate files and to have the main method located outside the class it is meant to run from. This approach enhances the code's readability, maintainability, and reusability.

In the realm of real-time software development, we establish classes and employ them within other classes, representing a more advanced methodology than before. To illustrate, consider a basic scenario where there exists a main function within a separate class.

It is possible to have multiple classes in separate Java files or within a single Java file. When defining several classes in one Java source file, it is advisable to name the file after the class containing the main method.

Example

Example

//Creating a Student class 

class Student{  

 //declaring fields or instance variables

 int id;  

 String name;  

}  

//Creating another class which contains the main() method  

class Main{  

 public static void main(String args[]){  

  Student s1=new Student();  

  System.out.println(s1.id);  

  System.out.println(s1.name);  

 }  

}

Output:

Output

0 

null

Explanation

Within the Java program above, the main function is presented in a separate class from the Student class. The Student class does not contain any methods defined for its two attributes, name and id. The main function is located in a different class named Main. Here, a default constructor is utilized to create an instance s1 of the Student type. The attributes name and id are assigned their default values - null for String and 0 for int - as they are not explicitly set.

Initializing an Object in Java

There are the following three ways to initialize an object in Java:

  • By Reference Variable
  • By Method
  • By Constructor
  • 1) Object Initialization through Reference Variable

Object initialization involves storing information within the object. To illustrate, let's consider a basic scenario where we initialize the object using a reference variable.

Example

Example

class Student{  

 int id;  

 String name;  

}  

public class Main{  

 public static void main(String args[]){  

  //Creating instance of Student class

  Student s1=new Student();  

  //assigning values through reference variable

  s1.id=101;  

  s1.name="Sonoo";  

  //printing values of s1 object

  System.out.println(s1.id+" "+s1.name);  

 }  

}

Output:

Output

101 Sonoo

Explanation

Within the Java program provided, there exist two classes known as Student and Main. Inside the Student class, two attributes, namely id and name, are declared. The entry point of the program, the main method, is explicitly declared within the Main class. Inside the main method, an object named s1 of type Student is instantiated using the new keyword. Subsequently, the id and name fields of s1 are initialized with the values 101 and "Sonoo".

It is possible to instantiate multiple objects and store data in them using a reference variable.

Example

Example

class Student{  

 int id;  

 String name;  

}  

public class Main{  

 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:

Output

101 Sonoo

102 Amit

Explanation

The Java program presented above demonstrates the creation and initialization of several objects of the Student class within the Main class. Two instances, namely s1 and s2, of the Student class have been instantiated using the new keyword. Following this, the name and id attributes of each object are set separately. Specifically, the ID is assigned the value 101 and the name is assigned "Sonoo" for object s1, while for object s2, the ID is set to 102 and the name is set to "Amit".

2) Object Initialization through Method

In this instance, we are instantiating two instances of the Student class and setting their values by calling the insertRecord method.

In this context, we showcase the data state of the objects by calling the displayInformation method.

Example

Example

class Student{  

 int rollno;  

 String name;  

 //Creating a method to insert record

 void insertRecord(int r, String n){  

  rollno=r;  

  name=n;  

 }  

 //creating a method to display information

 void displayInformation(){System.out.println(rollno+" "+name);}  

}  

//Creating a Main class to create objects and call methods

public class Main{  

 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:

Output

111 Karan

222 Aryan

Explanation

Within the Java code given, there are two distinct classes: Student and Main. Inside the Student class, there are attributes for roll number and name, accompanied by functions such as insertRecord and displayInformation for the purpose of setting and showcasing the information stored in these attributes. In the main function of the Main class, two instances of the Student class are instantiated, and the insertRecord methods of these instances are invoked to assign values to their roll numbers and names.

As depicted in the figure above, the object is allocated memory in the heap memory region. The reference variable points to the object that is allocated in the heap memory region. In this case, s1 and s2 are reference variables that point to the objects allocated in memory.

3) Object Initialization through a Constructor

In Java, object initialization through a constructor is a fundamental concept in object-oriented programming. Constructors are special methods within a class that are invoked when a new object of that class is created using the "new" keyword. They are responsible for setting initial values in the object's fields or performing necessary setup operations to establish the object's state. By automatically triggering during object creation, constructors ensure that objects are correctly initialized before they are utilized.

If you're new to programming, feel free to skip this section as we will cover constructor concepts in a later part of the tutorial.

Here is an illustration showcasing the initialization of an object using a constructor.

Example

Example

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 Main {  

    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:

Output

Student ID: 1

Student Name: John Doe

Student ID: 2

Student Name: Jane Smith

Explanation

In this instance, the Student object's id and name attributes are set up using a constructor that is specified within the Student class. The constructor requires two arguments: id and name. By employing this constructor to create student1 and student2 objects, the attributes of each object are initialized with the provided values. This approach guarantees that objects are instantiated with accurate initial values, simplifying the process of creating and utilizing objects in subsequent stages of the program.

Object and Class Example: Employee

Let's explore an instance where we are keeping track of employee records.

Example

Example

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 Main {    

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:

Output

101 ajeet 45000.0

102 irfan 25000.0

103 nakul 55000.0

Explanation

Within the given code, the Employee class is structured with id, name, and salary as its three attributes. It implements insert to assign values to these attributes and display to output the values. The main function in the Main class instantiates three Employee instances (e1, e2, and e3), setting specific values to their id, name, and salary attributes before invoking insert on each instance. Subsequently, display is called on each object to exhibit the object's initialization and information through method execution. The console then prints out the id, name, and salary values of each object.

Object and Class Example: Rectangle

An additional instance is provided to illustrate the management of data within the Rectangle class.

Example

Example

class Rectangle{  

 int length;  

 int width;  

 void insert(int l, int w){  

  length=l;  

  width=w;  

 }  

 void calculateArea(){System.out.println(length*width);}  

}  

public class Main{  

 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:

Output

55 

45

Explanation

The following Java code showcases the implementation of a Rectangle class, which contains attributes for length and width, as well as functionalities to assign dimensions and compute the area. Within the main function of the Main class, two instances of Rectangle are created and their dimensions are established through the insert operation.

What are the different ways to create an object in Java?

There are various methods available for instantiating an object in Java.

One way to create an object is by using the new keyword.

A prevalent method of instantiating an object in Java involves utilizing the new keyword in conjunction with a constructor. As an illustration,

Example

ClassName obj = new ClassName();

Memory is reserved for the object and its constructor is invoked to set it up.

Performed via the newInstance method.

This functionality is a member of the java.lang.Class class and is utilized for generating a fresh instance of a class dynamically during runtime. It triggers the constructor of the class that requires no arguments. For instance,

Example

ClassName obj = (ClassName) Class.forName("ClassName").newInstance();.
  1. By clone Method

The clone function generates a replica of a current object through executing a shallow duplicate. It provides a fresh object that mirrors the initial one. For instance,

Example

ClassName obj2 = (ClassName) obj1.clone();.
  1. By Deserialization

Creating objects through the process of deserialization involves reconstructing them from a sequence of bytes. This can be accomplished in Java by utilizing the ObjectInputStream class. The serialized object is fetched from a file or network, following which the readObject method is invoked to restore the object.

  1. Via Factory Method

Static factory methods are methods defined within a class that are responsible for creating instances of the class. They offer an alternative approach to object creation compared to invoking constructors directly and are useful for encapsulating the process of creating objects. One example of a static factory method is:

Example

ClassName obj = ClassName.createInstance().

We will learn these ways to create objects later.

Anonymous Object

Anonymous denotes a lack of a specific name. An entity lacking an identifier is referred to as an anonymous entity. Such entities are typically utilized solely during their instantiation.

When an object needs to be utilized just once, employing an anonymous object proves to be a viable solution. An illustration of this is:

Example

new Calculation();//anonymous object

Calling a method through an anonymous object

Example

Calculation c=new Calculation();

c.fact(5);

Calling method through an anonymous object

Example

new Calculation().fact(5);

Let's explore a comprehensive example showcasing an anonymous object in the Java programming language.

Example

Example

class Main{  

 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 Main().fact(5);//calling method with anonymous object  

}  

}

Output:

Output

Factorial is 120

Explanation

The Java program presented above is designed to determine the factorial of a specified number, denoted as 'n'. Within the Main class, there exists a method called fact responsible for calculating the factorial. Subsequently, the result is displayed in the console. The utilization of an anonymous object of the Main class, along with the immediate execution of its fact method with the argument 5 within the main function, showcases the application of anonymous objects in Java for singular method invocations.

Creating Multiple Objects by One Type Only

In programming, we have the ability to instantiate multiple objects of a single type, similar to how we work with primitive data types.

Initialization of Primitive Variables

Example

int a=10, b=20;

Initialization of Reference Variables

Example

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see an example.

Example

Example

//Java Program to illustrate the use of the 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 Main{  

 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:

Output

55 

45

Explanation

This Java program showcases the implementation of a Main class featuring length and width as its instance variables. Within this class, there are functions to determine the area of a rectangle and input dimensions. Within the main function of the Main class, a pair of Rectangle instances (r1 and r2) are created in a single line using a comma-separated approach, illustrating the capability to instantiate numerous objects of identical type at once. The insert method is utilized to define the dimensions of each object, followed by invoking the calculateArea function to compute and display the area of each rectangle.

Real World Example: Account

File: TestAccount.java

Example

Example

//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 Main{  

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:

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 Java program includes an Account class that simulates basic banking operations like depositing, withdrawing, checking balance, and displaying account details. It encompasses attributes such as account number, account holder's name, and balance. The Main class's main method is responsible for creating, initializing, and showcasing account details for an Account object named a1. Subsequently, the account undergoes deposit and withdrawal operations, followed by balance verification after each transaction.

Difference Between Class and Object in Java

Feature Class Object
Definition A class is a blueprint or template for creating objects. It is an instance of a class.
Type It is a logical entity. It is a real-world entity.
Memory Allocation Class definition does not occupy memory. It occupies memory when an object is created.
Keyword It is created by using the class keyword. It is created by using the new keyword and a class constructor.
Contains It contains properties and behaviors that an object will have. It is used to access the properties and behaviors defined in the class.
Existence Exists only in source code. Exists in runtime (in memory).
Usage Defines the structure and behavior of objects. Represents an entity with actual values.
Syntax class ClassName{ } ClassName objectName = new ClassName();
Life It exists until the program runs. It exists as long as the object is referenced in the program.
Inheritance The classes can be extended using inheritance. It cannot be inherited because objects are specific instances.

Input Required

This code uses input(). Please provide values below: