• Articles

What Is Classes and Objects in Java?

What Is Classes and Objects in Java?

Table of content

Show More

Java is one of the best programming languages, learning about classes and objects is important because they allow us to create efficient and reusable code, making our programs more flexible and easier to manage. With their ability to organize code and facilitate seamless interaction, Java classes and objects empower developers to create robust and efficient applications. This article will provide you with clear explanations and practical examples of working with classes and objects in Java and make you learn the fundamentals of it.

To improve your Java skills and start coding like a pro, watch our YouTube video!

Video Thumbnail

What is the Class in Java?

What is Class in Java?

In Java, a class is a template that defines the structure and behavior of objects. It serves as a blueprint for creating objects that belong to a particular type or class. A class encapsulates data (in the form of variables) and methods (functions) that operate on that data. It allows you to create multiple instances of objects with similar properties and behaviors. 

In java object oriented programming, a java class object serves as a blueprint for creating instances of that class, encapsulating data and behavior within the object.

Classes help organize and manage code by providing a way to group related data and functionality together. Using Java classes, you can create objects with their own unique state (data) and behavior (methods), enabling you to write modular, reusable, and organized code. The Java Object class serves as the root class for all other classes, providing fundamental methods like equals(), toString(), and hashCode(), essential for object manipulation and comparison.

Types of Classes in Java

In Java, there are several types of classes that serve different purposes and play important roles. 

  • Static Class: A static class in Java is a nested class that belongs to its outer class rather than an instance of the outer class. It is used when you want to group functionality that doesn’t rely on the specific state of an object. Static classes can contain static variables and static methods and can be accessed directly using the class name.
public class OuterClass {
    private static int outerStaticField = 5;
    private int outerInstanceField = 10;

    public static class NestedClass {
        private int nestedInstanceField = 20;

        public void printFields() {
            System.out.println("Outer static field: " + outerStaticField);
            // System.out.println("Outer instance field: " + outerInstanceField); // Cannot access non-static field
            System.out.println("Nested instance field: " + nestedInstanceField);
        }
    }

    public static void main(String[] args) {
        OuterClass.NestedClass nestedObject = new OuterClass.NestedClass();
        nestedObject.printFields();
    }
}
  • Final Class: In Java, a final class is one you cannot inherit or extend with any other class. It is commonly used to create immutable classes, which means their state cannot be changed once an object is created. Final classes prevent any further modification or extension of the class.
public final class FinalClass {
    private String message;

    public FinalClass(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void displayMessage() {
        System.out.println("Message: " + message);
    }
}
  • Abstract Class: An abstract class in Java is a class that cannot be instantiated directly but can only be used as a base for other classes. It serves as a blueprint for derived classes to provide common behavior and define abstract methods that its subclasses must implement. Abstract classes are useful when providing a common interface for a group of related classes.
public abstract class AbstractClass {
    private String name;

    public AbstractClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public abstract void displayInfo(); // Abstract method

    public void commonMethod() {
        System.out.println("This is a common method in the abstract class.");
    }
}

Check out this blog to learn about purpose of abstract class in java!

  • Concrete Class: A concrete class in Java is a class that can be instantiated and used to create objects. Unlike abstract classes, concrete classes implement all their methods and can be used directly. They are used to define specific behavior and attributes of objects.
public class ConcreteClass {
    private String name;

    public ConcreteClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void displayInfo() {
        System.out.println("Name: " + getName());
    }

    public static void main(String[] args) {
        ConcreteClass obj = new ConcreteClass("John");
        obj.displayInfo();
    }
}
  • Singleton Class: A singleton class in Java is a class that allows only one instance of itself to be created. It ensures a single point of access to the object throughout the application. Singleton classes are commonly used when you need a single, shared class instance, such as a database connection or a logger.
public class SingletonClass {
    private static SingletonClass instance;
    private String data;

    private SingletonClass() {
        // Private constructor to prevent direct instantiation
        data = "Hello, Singleton!";
    }

    public static SingletonClass getInstance() {
        if (instance == null) {
            synchronized (SingletonClass.class) {
                if (instance == null) {
                    instance = new SingletonClass();
                }
            }
        }
        return instance;
    }

    public String getData() {
        return data;
    }

    public void setData(String newData) {
        data = newData;
    }
}

Check out the list of Hibernate Interview Questions to prepare for upcoming interviews.

  • POJO Class: POJO stands for “Plain Old Java Object.” A POJO class in Java is a simple Java class that encapsulates data and provides getter and setter methods for accessing and modifying that data. It does not need to extend any specific class or implement any interfaces. POJO classes are used for data transfer objects (DTOs) or entity classes in Java frameworks.
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
  • Inner Class: An inner class in Java is a class that is defined inside another class. It can access the outer class members (variables, methods), including private members. Inner classes help create logically related classes and can have different access modifiers (public, private, protected) based on the requirements.
public class OuterClass {
    private int outerField;

    // Nested Inner Class
    public class InnerClass {
        private int innerField;

        public InnerClass(int innerField) {
            this.innerField = innerField;
        }

        public void display() {
            System.out.println("Outer Field: " + outerField);
            System.out.println("Inner Field: " + innerField);
        }
    }

    // Local Inner Class
    public void createLocalInnerClass() {
        int localVar = 10;

        class LocalInnerClass {
            public void display() {
                System.out.println("Local Variable: " + localVar);
            }
        }

        LocalInnerClass localInnerObj = new LocalInnerClass();
        localInnerObj.display();
    }

    // Anonymous Inner Class
    public void createAnonymousInnerClass() {
        InterfaceExample interfaceObj = new InterfaceExample() {
            @Override
            public void display() {
                System.out.println("Anonymous Inner Class");
            }
        };

        interfaceObj.display();
    }

    // Static Nested Class
    public static class StaticNestedClass {
        private static int nestedField;

        public StaticNestedClass(int nestedField) {
            this.nestedField = nestedField;
        }

        public void display() {
            System.out.println("Nested Field: " + nestedField);
        }
    }

    public interface InterfaceExample {
        void display();
    }

    public static void main(String[] args) {
        OuterClass outerObj = new OuterClass();
        outerObj.outerField = 5;

        // Nested Inner Class
        OuterClass.InnerClass innerObj = outerObj.new InnerClass(10);
        innerObj.display();

        // Local Inner Class
        outerObj.createLocalInnerClass();

        // Anonymous Inner Class
        outerObj.createAnonymousInnerClass();

        // Static Nested Class
        OuterClass.StaticNestedClass staticNestedObj = new OuterClass.StaticNestedClass(15);
        staticNestedObj.display();
    }
}
  • Superclass: A superclass in Java is a class from which other classes inherit properties and methods. It serves as a base class or parent class for its subclasses. Subclasses can inherit and extend the functionality of the superclass while adding their specific behavior. Inheritance helps achieve code reuse and hierarchical organization of classes.
public class Superclass {
    private String name;

    public Superclass(String name) {
        this.name = name;
    }

    public void display() {
        System.out.println("Superclass Name: " + name);
    }
}
  • Subclass: A subclass in Java is a class that inherits properties and methods from a superclass. It extends the functionality of the superclass by adding new methods or overriding existing ones. Subclasses are used to specialize and customize the superclass’s behavior to meet specific requirements.
public class Subclass extends Superclass {
    private int age;

    public Subclass(String name, int age) {
        super(name); // Call to superclass constructor
        this.age = age;
    }

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

Are you ready to advance your Java knowledge? Enroll in our thorough Java course today to maximize your potential!

How to Create a Class in Java?

How to Create a Class in Java?

Here’s a step-by-step guide on how to create a class in Java:

  • Open a text editor or an Integrated Development Environment (IDE) like Eclipse or IntelliJ.
  • Start by defining the class using the ‘class’ keyword, followed by the class name. Make sure to use proper naming conventions, such as starting with an uppercase letter and using camel case (e.g. ‘public class MyClass’).
  • Within the class body, you can define various components, such as variables, methods, constructors, and more. Let’s start with adding variables, also known as class fields. These variables represent the data or attributes associated with the class. For example, you can declare a variable to store a person’s name: ‘private String name;.’
  • Next, you can add methods to the class. Methods are functions that define the behavior or actions that objects of the class can perform. For instance, you can create a method to display the name: ‘public void displayName() { System.out.println(name); }.’
  • You can also add constructors to initialize the objects of the class. Constructors are special methods with the same name as the class. They are used to set initial values to the variables or perform any necessary setup. For example: ‘public MyClass(String initialName) { name = initialName; }.’
  • Additionally, you can include other features in the class, such as getters and setters for accessing and modifying the class fields, static variables and methods that belong to the class itself rather than individual objects, and more advanced concepts like inheritance and interfaces.
  • Save the Java file with a ‘.java’ extension, using the same name as the class. For example, if your class is named ‘MyClass,’ save the file as ‘MyClass.java.’
  • Once the class is created, you can create objects (also known as instances) of the class in other parts of your program using the ‘new’ keyword. For example: ‘MyClass myObject = new MyClass(“John”);.’

That’s it! You have successfully created a class in Java.

public class MyClass {
    private String name;

    public MyClass(String initialName) {
        name = initialName;
    }

    public void displayName() {
        System.out.println(name);
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass("John");
        myObject.displayName();
    }
}

Get a Complete Hands-on on Java through our Java Tutorial.

What are Objects in Java?

What are Objects in Java?

In Java, objects are the fundamental building blocks of a program. An object represents a specific class instance and embodies data (attributes) and behavior (methods). Objects allow us to model and manipulate real-world entities or concepts in our programs. They encapsulate related data and functionality, providing a way to interact with and manipulate the data through method calls. Objects can communicate with each other by invoking methods and exchanging data, enabling the implementation of complex and dynamic systems in Java programs.

Get 100% Hike!

Master Most in Demand Skills Now!

Initialization of Classes and Objects

In Java, classes and objects are initialized through different methods based on the program’s specific needs. Here are the common ways of initializing classes and objects:

Initialization by Reference Variable:

Objects can be created and initialized by assigning a reference variable to a new class instance using the ‘new’ keyword. This method is straightforward and commonly used.

For example:

ClassName objectName = new ClassName();

Initialization by Method:

Objects can also be created and initialized through methods. In this approach, a method within a class is responsible for creating and returning an object of that class. This method allows additional flexibility and logic during object creation.

For example:

public ClassName createObject() {
    ClassName objectName = new ClassName();
    // Additional initialization code if needed
    return objectName;
}

Initialization by Constructor:

Java Constructors are special methods in a class that are used to initialize objects. They have the same name as the class and are invoked using the ‘new’ keyword. Constructors can have parameters to pass values during object creation.

For example:

public class ClassName {
    public ClassName() {
        // Initialization code
    }
}
// Object creation using constructor
ClassName objectName = new ClassName();

Here is an example of a code demonstrating the initialization of classes and objects in Java:

public class Person {
    private String name;
    private int age;

    public Person() {
        // Default constructor
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    public static void main(String[] args) {

        // Initialization by Reference Variable
        Person person1 = new Person();
        person1.name = "John Doe";
        person1.age = 25;
        person1.displayInfo();

        // Initialization by Constructor
        Person person2 = new Person("Jane Smith", 30);
        person2.displayInfo();

        // Initialization by Method
        Person person3 = createPerson("Mike Johnson", 40);
        person3.displayInfo();
    }

    public static Person createPerson(String name, int age) {
        Person person = new Person();
        person.name = name;
        person.age = age;
        return person;
    }
}

Want to ace your next Java interview? Check out our recent blog post about the most common Java interview questions and answers!

Class Vs. Object In Java

Class Vs. Object In Java

Here is a tabular comparison between classes and objects in Java:

CriteriaClass in JavaObject In Java
DefinitionClass is a blueprint or template for objects.Object is a specific instance of a class.
Memory ConsumptionClass in Java does not consume memory on its own.Object in Java occupies memory when instantiated.
Variables and MethodsIt contains class variables and methods.It holds instance variables and instance methods.
InstantiationCan be instantiated multiple times.Refers to a particular instance of a class.
UsageClass is used to organize related functionalityObject represents real-world entities or concepts.

Conclusion

In conclusion, classes and objects in Java are the dynamic duo of Java programming. Classes act as blueprints, defining the structure and behavior of objects. Objects, on the other hand, bring those blueprints to life, representing specific instances with their characteristics. By understanding how to create classes and objects, learners gain the power to organize code, create reusable components, and model real-world entities.

Whether it’s initializing objects, differentiating between classes and objects, or exploring various class types, mastering these concepts highlighted in the blog will help you unlock the fundamentals of classes and objects in Java.

Join our today and interact with other developers all over the world! Join now and push your Java abilities to new heights!

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch