Home » Classes and Objects in Java

Classes and Objects in Java

Classes and Objects in Java

Introduction

Everything in Java is associated with classes and objects, along with its attributes and methods.Being an Object-oriented programming language, Java incorporates many of its features. Java deals with classes and objects, and their attributes and methods. Classes and objects are two crucial concepts that every programmer must learn. An object has behavior and states and class is a blueprint of an object. Class defines how the object will behave and what it will contain.In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.

Java Class

A Java classes is a blueprint or template used to create object. It serves as a fundamental building block in Java programming, encapsulating data (fields) and behaviors (methods) into a single unit. you specify the attributes and behaviors that objects of that class will possess. The attributes, also known as fields or instance variables, represent the state or characteristics of objects. The behaviors, represented by methods, define the actions that objects can perform.

Classes provide a way to model real-world entities or abstract concepts in software. They promote code organization, reusability, and maintainability by encapsulating related functionalities into cohesive units. Additionally, classes support features such as inheritance, polymorphism, and encapsulation, which are core principles of object-oriented programming.

a Java class defines the structure and behavior of objects, serving as a blueprint for creating instances of that class. It plays a central role in object-oriented programming and facilitates the development of modular, scalable, and maintainable software systems.

For example, Student is a class while a particular student named Ravi is an object.

Properties of Java Classes

  • A Java class serves as a blueprint for creating objects and doesn’t take up memory.
  • It comprises variables of various types and methods. You can include data members, methods, constructors, nested classes, and interfaces within a class.
  • It acts as a template for organizing and defining the behaviour of objects in your program.

Syntax of Java Classes

package com.example;

import java.util.ArrayList;

public class MyClass {
    private int age;

    public MyClass(int age) {
        this.age = age;
    }

    public void display() {
        System.out.println("Age: " + age);
    }
}
Java

This syntax defines a class named MyClass in the com.example package, with a private field age, a constructor that initializes age, and a method display() to print the age.

Components of Java Class

In Java, a class serves as a blueprint for creating objects. It encapsulates data and behavior into a single unit. Here are the main components of a Java class:

  • Class Declaration: The class declaration defines the name of the class and any inheritance or interfaces it implements.
public class MyClass {
    // class body
}
Java
  • Fields (Instance Variables): Fields represent the state or attributes of objects created from the class.
private int age;
Java
  • Constructors: Constructors initialize objects of the class. They have the same name as the class and are called when objects are created.

public MyClass(int age) {
    this.age = age;
}
Java
  • Methods: Methods define the behavior or actions that objects of the class can perform.

public void display() {
    System.out.println("Age: " + age);
}

Java
  • Access Modifiers: Access modifiers control the accessibility of class members (fields, constructors, methods).

public class MyClass {
    private int age;
    public MyClass(int age) {
        this.age = age;
    }
    public void display() {
        System.out.println("Age: " + age);
    }
}
Java

These components collectively define the structure and behavior of a Java class, allowing for the creation of objects with specific characteristics and functionality.

Principles to create a class

To create a class, these principles should be followed-

  • Single Responsibility Principle- A class should have only a single purpose and should be well-defined.
  • Open Closed Responsibility- A class should be able to extend another class without modifying the class.
  • Liskov Substitution Responsibility- A derived class should be substitutable for its base class.
  • Dependency Inversion Principle- High-level modules should not import anything from low-level modules and should depend on abstractions.
  • Interface Segregation Principle- A client should not be exposed to methods it does not need.

Rules for creating a class

In order to create a class, these rules must be followed-

  • The “class” keyword should be used.
  • The name of the class should start with an uppercase letter.
  • The Java file can contain any number of classes but should not have more than one public class. The file name should be named after the public class followed by the “.java” extension.
  • One class should only inherit another single class.

Types of classes

There are two types of classes-

  1. Built-in classes
  2. User-defined classes

Built-in classes- The built-in classes are those which are pre-defined by the developers in JDK. We can directly use them in our programs. Examples include-

  • java.util.Date
  • java.util.LinkedList

User-defined classes- So as the name suggests, user-defined classes are the classes created by the user. We can add our functionality to the classes.

Example

here’s a short Java code snippet demonstrating the syntax of a class:

public class MyClass {
    // Fields
    private int age;
    private String name;
    
    // Constructor
    public MyClass(int age, String name) {
        this.age = age;
        this.name = name;
    }
    
    // Method
    public void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    // Main method (for demonstration)
    public static void main(String[] args) {
        // Creating an object of MyClass
        MyClass myObject = new MyClass(25, "John");
        
        // Calling a method on the object
        myObject.displayInfo();
    }
}
Java

In this code snippet:

  • The MyClass class is defined with two private fields age and name.
  • It has a constructor MyClass(int age, String name) to initialize the fields.
  • There’s a method displayInfo() to display information about the object.
  • In the main() method, an object of MyClass named myObject is created, and the displayInfo() method is called on it to print the information.

Java Objects

A Java object is an instance of a class. It represents a specific realization of the class blueprint, with its own unique set of data values for the fields defined in the class.

Objects are created using the new keyword followed by the class name, along with any required arguments to initialize the object’s state. Each object created from a class has its own separate memory space allocated for its fields, allowing it to maintain its own state independent of other objects created from the same class.

Objects encapsulate both data (fields) and behavior (methods) into a single unit. They can interact with each other by invoking methods and accessing fields. In essence, objects are the building blocks of object-oriented programming in Java, allowing developers to model real-world entities and create modular, reusable, and maintainable software components.

An object consists of :

  1. State: It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
  3. Identity: It gives a unique name to an object and enables one object to interact with other objects.
java-object.png

Note: –

When we create an object which is a non primitive data type, it’s always allocated on the heap memory.

Syntax of an object

The syntax for creating an object in Java is:


ClassName objectName = new ClassName();

Java

For example:


Car myCar = new Car();

Java

Here, Car is the class name, myCar is the object name, and new Car() instantiates a new object of the Car class.

Initializing an object

In Java, we can initialize objects in 3 ways-

  • By reference variable
  • By method
  • By constructor

By reference variable– Initialization of an object means storing the data in the object. Let us understand this with an example-


public class MyClass {
    public static void main(String[] args) {
        // Initialize the object by reference variable in a single line
        MyClass myObject = new MyClass();
        
        // Access methods or fields of the object
        myObject.myMethod();
    }
    
    public void myMethod() {
        System.out.println("Object initialized successfully!");
    }
}
Java

In this code, myObject is the reference variable, and it’s initialized to refer to a new object of the MyClass class in a single line using the new keyword. This single line achieves both declaration and instantiation of the object. After initialization, you can directly access methods or fields of the object using the reference variable.

Anonymous Objects

An anonymous object is an object that is created without assigning it to a reference variable. It is typically used for performing a single operation and is not intended to be reused.

Here’s an example of creating and using an anonymous object:


public class MyClass {
    public void showMessage(String message) {
        System.out.println("Message: " + message);
    }

    public static void main(String[] args) {
        // Creating and using an anonymous object
        new MyClass().showMessage("Hello, World!");

        // Another example with method chaining
        new MyClass().showMessage("Hello").showMessage("World");
    }
}

Java

In this example, new MyClass() creates an anonymous object of the MyClass class. Instead of assigning it to a reference variable, we immediately call the showMessage() method on the anonymous object, passing the message “Hello, World!” as an argument.

Anonymous objects are useful when you need to perform a single operation without storing the object’s reference for future use. They can be convenient for short-lived operations or when you don’t want to clutter your code with unnecessary reference variables.

Example

Here’s an example of a Java class and object

public class Car {
    // Attributes
    private String brand;
    private String model;
    private int year;

    // Constructor
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

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

    public static void main(String[] args) {
        // Creating an object of Car class
        Car myCar = new Car("Toyota", "Camry", 2022);
        
        // Calling method to display car details
        myCar.displayDetails();
    }
}
Java

Difference Between Java Classes and Object

Conclusion

In Java classes and object are fundamental concepts. A class serves as a blueprint or template for creating objects, defining attributes and behaviours. Objects are instances of classes, representing concrete realizations of the class blueprint. When you create an object, you allocate memory for it and initialize its attributes. Java supports object-oriented principles such as encapsulation, inheritance, and polymorphism, enabling modular, reusable, and maintainable code. Classes and objects are fundamental concepts in Java programming, enabling developers to model real-world entities and build complex systems.

Frequently Asked Questions

Q1. What is a Java class?

A Java class is a blueprint or template for creating objects. It defines the attributes and behaviors that objects of that class will have.

Q2. How do you declare a class in Java?

You declare a class in Java using the class keyword followed by the class name and a code block containing the class’s fields (attributes) and methods.

Q3. What is an object in Java?

An object in Java is an instance of a class. It represents a concrete realization of the class blueprint and holds specific data and state.

Q4. How do you create an object in Java?

To create an object in Java, you use the new keyword followed by the class name and optional constructor arguments if the class has a constructor.

Q5. What is a constructor in Java?

A constructor in Java is a special method that is invoked when an object of a class is created. It initializes the object’s state and can take arguments to set initial values for the object’s attributes.