Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
What is Class in Java? - Objects and Classes in Java {Explained}

What is Class in Java? - Objects and Classes in Java {Explained}

02 Dec 2024
Intermediate
35.5K Views
20 min read
Learn with an interactive course and practical hands-on labs

Free Java Foundation Course

Java Class and Object

Fundamental ideas in Java programming are Classes and objects in Java, which resemble real-world things with states, behaviors, and characteristics. Classes, which include variables to hold object states and methods to specify their behavior, allow programmers to model their code after actual entities in the real world.

Java's natural object-oriented programming capabilities are built on this powerful combination, which makes writing easier. If you want to get started with Java checkourJavatutorial to kickstart your learning journey.

Build your dream career as a full stack developer—sign up for our Java Full Stack Developer Certification Training today!

What is Java Classes?

An essential part of the Java language is the class, which contains objects with similar properties and specifies their data and behavior. It provides structure and efficiency for Java developers and serves as the blueprint for building objects.Abstraction in Java is an important aspect of object-oriented programming, where an object is an abstract concept in Java; it has no physical representation like variables or other types of data but instead acts as a template for entities being modeled within a program.

Java classes provide the framework for building models incorporating essential concepts like inheritance in Java, polymorphism in Java, abstraction, & encapsulation. They act as the design manual for the construction of objects, making Java development essential.

How to Create a Class in Java?

How to create a class in Java?

Properties of Java Classes

1. Class is Not a Real-World Entity:
  • A class is an abstract concept and acts as a blueprint for creating objects. It represents the definition but not the physical existence of an entity.
  • Example: A "Car" class defines properties like color, model, and speed but does not represent any specific car until instantiated.

2. Class Does Not Occupy Memory:

  • Unlike objects, classes themselves do not occupy memory until an object is created from the class.
  • Example: Declaring a class does not allocate space in memory until you create an object using the new keyword.

3. Class is a Grouping Mechanism:

  • A class is a logical container that groups variables (data members) and methods (functions).
  • These elements collectively define the behavior and state of objects created by the class.
  • Data Members: Variables that hold data specific to the objects of the class.
  • class Car {
        String color;
        int speed;
    }
    Methods: Functions that define the behavior or actions of the objects.
    void drive() {
        System.out.println("The car is driving.");
    }
    Constructor: A special method used to initialize objects when they are created.
    Car(String color, int speed) {
        this.color = color;
        this.speed = speed;
    }
    Nested Class: A class within another class, useful for logical grouping or encapsulation.
    class Outer {
        class Inner {
            void display() {
                System.out.println("This is a nested class.");
            }
        }
    }
    Interface: A blueprint for a class to implement, containing abstract methods.
    interface Vehicle {
        void start();
    }

Syntax of class in Java


access_modifier class<class_name>
{ 
  data member; 
  method; 
  constructor;
  nested class;
  interface;
}

Example 1: Example of the class program in Java


class Student {
int id; // data member (also instance variable)
String name; // data member (also instance variable)

public static void main(String args[])
{
 Student s1 = new Student(); // creating an object of
    // Student
 System.out.println(s1.id);
 System.out.println(s1.name);
}
}

Output

0
null

A Student is defined by this Java class and has two instance variables (name and id). In the main method, a Student (s1) instance is created, and its uninitialized variables—which most likely have default values of 0 for id and null for name—are printed.

Example 2: Simple Class with Methods and Constructor

This example demonstrates a basic class with a constructor and methods to initialize and display object properties.


// Class definition
class Car {
    // Data members (variables)
    String color;
    String model;
    int year;

    // Constructor to initialize the Car object
    Car(String color, String model, int year) {
        this.color = color;
        this.model = model;
        this.year = year;
    }

    // Method to display car details
    void displayDetails() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }

    // Method to start the car
    void startCar() {
        System.out.println(model + " is starting...");
    }
}

// Main class to test the Car class
public class Main {
    public static void main(String[] args) {
        // Creating objects of the Car class
        Car car1 = new Car("Red", "Toyota", 2022);
        Car car2 = new Car("Blue", "Honda", 2020);

        // Calling methods
        car1.displayDetails();
        car1.startCar();

        car2.displayDetails();
        car2.startCar();
    }
}
        

Example 3: Class with Nested Class

This example demonstrates how a nested class can be defined inside another class and how it can access the outer class's data members.


// Outer class
class OuterClass {
    // Data member of outer class
    String outerMessage = "This is the outer class.";

    // Nested class inside the outer class
    class InnerClass {
        // Method in the inner class
        void displayMessage() {
            System.out.println(outerMessage);  // Accessing outer class data member
            System.out.println("This is the inner class.");
        }
    }
}

// Main class to test nested class functionality
public class Main {
    public static void main(String[] args) {
        // Creating an object of the OuterClass
        OuterClass outerObject = new OuterClass();
        
        // Creating an object of the InnerClass through the outer class object
        OuterClass.InnerClass innerObject = outerObject.new InnerClass();

        // Calling the method in the inner class
        innerObject.displayMessage();
    }
}
        

How to Create an Object in Java?

There are many different ways to create objects in Java, those are:

1. Define a Class

Before you can create an object in Java, you first need to define a class. A class is a blueprint or template from which objects are created. It contains data members (variables) and methods (functions) that describe the properties and behavior of the objects.

// Class definition
class Car {
    // Data members (attributes)
    String model;
    String color;
    int year;

    // Constructor to initialize the object
    Car(String model, String color, int year) {
        this.model = model;
        this.color = color;
        this.year = year;
    }

    // Method to display car details
    void displayDetails() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }
}        

2. Create an Instance of the Class

To create an object from the class, you need to declare a reference to the class and use the new keyword to allocate memory for the object. The new keyword is used to create an instance of the class, i.e., an object.

Car myCar = new Car("Toyota", "Red", 2022);       

In this line, Car is the class, myCar is the object reference (instance), and new Car(...) creates the actual object, initializing it with the provided values "Toyota", "Red", and 2022.

3. Access the Object

Once an object is created, you can access its properties (data members) and behaviors (methods) using the object reference. You can call methods or modify the values of data members through the object.

myCar.displayDetails();        

The method displayDetails() is called on the object myCar. This will print out the values of the car's model, color, and year.

Complete Example

Here is a complete Java program demonstrating the above steps:

// Define the Car class
class Car {
    String model;
    String color;
    int year;

    // Constructor to initialize the Car object
    Car(String model, String color, int year) {
        this.model = model;
        this.color = color;
        this.year = year;
    }

    // Method to display car details
    void displayDetails() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }
}

// Main class to create and access the object
public class Main {
    public static void main(String[] args) {
        // Create an instance (object) of the Car class
        Car myCar = new Car("Toyota", "Red", 2022);

        // Accessing the object's method
        myCar.displayDetails();
    }
}       

Different ways to create objects in Java

1. Using the new keyword:

The developer can create an object of a class using the new keyword followed by the constructor of the class.

Example:


ClassName objectName = new ClassName();

With this line of code, an object of the class "ClassName" is created and assigned to the variable "objectName."

2. Using Class.forName() method:

The developer can create an object of a class using the Class.forName() method, which returns a Class object.

Example:


Class className = Class.forName("ClassName");
ClassName objectName = (ClassName) className.newInstance();

In this code, the class "ClassName" is dynamically loaded by "Class.forName("ClassName")" and then created by "className.newInstance()" and assigned to the variable "objectName" after being cast to the proper type.

3. Using clone() method:

The programmers can create a new object by cloning an existing object using the clone() method.

Example:


ClassName object1 = new ClassName();
ClassName object2 = object1.clone();

According to this example, "object1" generates an instance of "ClassName," whereas "object2 = object1.clone()" makes a new instance of "object2" that is a copy or clone of "object1." You can duplicate objects with the same characteristics and behaviors thanks to this.

4. Using object deserialization:

The programmers can create an object by deserializing the object from a file or network stream

Example:


ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
ClassName objectName = (ClassName) objectInputStream.readObject();

In this example, the "ObjectInputStream" is initially set up to read serialized data from the "inputStream" and to deserialize that data into an instance of the "ClassName" class, which is then assigned to the variable "objectName."

5. Using Factory Method:

The developer can use a Factory Method to create objects of a class by calling a method that returns an instance of the class.

Example:


public static ClassName createObject() {
  return new ClassName();
}
ClassName objectName = ClassName.createObject();

In the "ClassName" class, the static function "createObject" in this example defines a brand-new instance of "ClassName." The "createObject" function is then used, which is a standard pattern for generating objects with specified initialization logic, to create an instance of "ClassName" called "objectName".

6. Using Dependency Injection:

Users can create objects by injecting dependencies into the class constructor or using a framework to manage object creation.

Example:


public class MyClass {
  private Dependency dependency;
  public MyClass(Dependency dependency) {
    this.dependency = dependency;
  }
}
MyClass objectName = new MyClass(new Dependency());

In this case, a constructor that initializes a private instance variable named "Dependency" and a class named "MyClass" is defined. Then, it establishes a dependency between the two classes by creating an instance of "objectName" of "MyClass" with a fresh instance of "Dependency" as a constructor argument.

Anonymous Object in Java

Java Objects

Java objects, which represent actual real-world objects, are instances of classes. They include data (attributes) and behaviors (methods) associated with a particular class.

Declaring Objects (Also called instantiating a class)

In Java, declaring an object entails making instances of a class. This includes naming a variable, the class type, and the class constructor before using the "new" keyword.

Example

ClassName objectName = new ClassName();

Initializing a Java object

When a Java object is initialized, its initial state is established by giving its attributes (data members) values. Usually, constructors or setter methods are used for this.

Example


public class Student {  private String name;
  private int age;  // Constructor to initialize the object
  public Student(String name, int age) {
    this.name = name;
    this.age = age;
  }
}// Initializing a Student object
Student student = new Student("Mahesh", 20);

The "Student" class is defined by this code and has a private name and age attributes as well as a constructor to initialize them. It then establishes the starting state of a "student" object with the name "Mahesh" and the age of 20.

Difference between Class and Object in Java

Parameter Class Object
DefinitionA class is a blueprint or a template that defines the properties and behavior of objects.An object is an instance of a class that has actual values for those properties.
UsageA class is used to create objects, which are instances of that class.An object is an instance of a class that has been created using the constructor of that class.
PropertiesA class defines the properties that objects of that class will have. These properties are defined using variables.An object has values for those properties.
MethodsA class also defines the behavior that objects of that class will have. This behavior is defined using methods.An object can call these methods to perform specific tasks.
Memory allocationA class is not allocated memory in the Java Virtual Machine (JVM).An object is allocated memory when it is created using the "new" keyword.

Summary

Objects and Classes in Java are powerful concepts that can help create efficient code. It is important to become familiar and comfortable with the nuances of this fundamental object-oriented programming language features to be able to utilize its full potential. Through practice and collaboration, one can grow significantly as a programmer by mastering fundamentals like Java Class and Object. Hence, enroll in our Full Stack Java Course.

FAQs

An object is an instance of a class that represents a real-world entity, whereas a class in Java is a blueprint or template that determines the structure and behavior of objects.

The "class" keyword is used to define a class in Java, which has data members (attributes) as well as methods (behaviors).

In Java, use the "new" keyword followed by the class constructor to create an instance of a class: objectName className = new classname();

Java provides a variety of constructors, cloning, deserialization, or object initialization block methods for creating objects.

In Java, the main difference between a class and an object is that the former is a blueprint or template, whilst the latter is an instance made from the former with its own particular data.

In Java, an anonymous object is one that is created without being assigned to any variables and is normally used for a single operation. For instance: the new method new ClassName();

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this