Java Programming Classes And Objects Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    12 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Java Programming Classes and Objects

Java Programming: Classes and Objects

Introduction to Classes and Objects in Java

In Java, classes and objects are the two main concepts that define the structure and behavior of your application. They are the building blocks of OOP, allowing you to create reusable and maintainable code. A class acts as a blueprint or template for creating objects, while an object is a specific instance of a class.

Defining a Class

A class in Java defines the attributes (data) and behaviors (methods) that its objects can have. You define a class using the class keyword followed by the class name. Here’s the basic syntax:

public class Car {
    // Attributes (fields)
    private String color;
    private int year;
    private String model;

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

    // Methods
    public void startEngine() {
        System.out.println("Engine started.");
    }

    public void drive() {
        System.out.println("Car is driving.");
    }

    public String getColor() {
        return color;
    }

    public int getYear() {
        return year;
    }

    public String getModel() {
        return model;
    }
}
  • Attributes: These are variables that store the data associated with the class. In the above example, color, year, and model are attributes.
  • Methods: These are functions that define the actions that the objects of the class can perform.
  • Constructor: This is a special method used to initialize objects when they are created. Constructors have the same name as the class and no return type (not even void).

Creating an Object

To use a class, you need to create an object (or multiple objects). An object can perform operations defined by the methods and access the data stored in the attributes. To create an object, you allocate memory for the class instance and then instantiate it.

Here's how you create an object of the Car class:

public class Main {
    public static void main(String[] args) {
        // Creating an object of Car using the constructor
        Car myCar = new Car("Red", 2023, "Mustang");

        // Accessing object properties and methods
        System.out.println(myCar.getColor()); // Output: Red
        System.out.println(myCar.getYear()); // Output: 2023
        System.out.println(myCar.getModel()); // Output: Mustang

        // Calling methods on the object
        myCar.startEngine(); // Output: Engine started.
        myCar.drive(); // Output: Car is driving.
    }
}
  • Declaration: The statement Car myCar; declares a Car type variable named myCar.
  • Instantiation: The statement new Car("Red", 2023, "Mustang"); creates a new Car object.
  • Initialization: The new operator also triggers the execution of the constructor, passing "Red", 2023, and "Mustang" as arguments to initialize the myCar object.

Important Concepts

  1. Encapsulation:

    • Encapsulation is the bundling of data (attributes) and methods (functions) into a single unit or class. It also restricts direct access to some of an object’s components, which can prevent the accidental modification of data.
    • In the Car class example, the attributes color, year, and model are marked as private which means they can only be accessed within the Car class. You provide public getter methods (getColor(), getYear(), getModel()) to access these attributes from outside the class.
  2. Inheritance:

    • Inheritance allows a new class (subclass) to inherit properties and methods from an existing class (superclass).
    • Consider an example where you create a subclass called ElectricCar that inherits from the Car class:
      public class ElectricCar extends Car {
          private int batteryCapacity;
      
          public ElectricCar(String color, int year, String model, int batteryCapacity) {
              super(color, year, model); // Calls the parent class constructor
              this.batteryCapacity = batteryCapacity;
          }
      
          public int getBatteryCapacity() {
              return batteryCapacity;
          }
      
          @Override
          public void startEngine() {
              System.out.println("The engine is electric and starts quietly.");
          }
      }
      
    • The ElectricCar class extends the Car class, inheriting its attributes and methods. It also introduces a new attribute batteryCapacity and overrides the startEngine() method to provide a different implementation.
  3. Polymorphism:

    • Polymorphism enables methods to do different things based on the object it is acting upon. One method can behave differently on different objects.
    • For instance, consider the startEngine() method in both Car and ElectricCar classes. Despite having the same name, they produce different outputs when called on different objects.
    public class Main {
        public static void main(String[] args) {
            Car myCar = new Car("Red", 2023, "Mustang");
            ElectricCar myElectricCar = new ElectricCar("Blue", 2022, "Tesla Model S", 100);
    
            myCar.startEngine(); // Output: Engine started.
            myElectricCar.startEngine(); // Output: The engine is electric and starts quietly.
        }
    }
    
  4. Object State and Behavior:

    • An object's state represents its properties at a given time, defined by its attributes.
    • An object's behavior defines how it reacts with its environment or other objects, as defined by its methods.
  5. Access Modifiers:

    • Access modifiers like public, private, protected, and package-private (default) control the visibility of classes, methods, and variables.
    • public: Accessible from anywhere.
    • private: Accessible only within its own class.
    • protected: Accessible within its own package and by subclasses in other packages.
    • Package-private (without any modifier): Accessible only within its own package.

Key Points to Remember

  • Classes are templates while objects are instances of these classes.
  • Use constructors to initialize objects.
  • Encapsulation, inheritance, and polymorphism are essential OOP concepts that make Java powerful.
  • Access modifiers help in maintaining the security and integrity of the code.
  • Methods represent the behaviors of the objects, and attributes store their state.
  • Always aim to design classes in such a way that promotes reusability, maintainability, and readability.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Java Programming Classes and Objects

Chapter: Java Programming - Classes and Objects

Introduction

In Java, everything is associated with classes and objects. A class is like a blueprint or a template for creating objects while an object is an instance of a class.

1. Writing a Simple Class

Let’s start by writing a simple class in Java.

Example Code:

// Define a class named 'Car'
public class Car {
    // Declaring fields (or variables) of the class
    String color;
    String model;

    // Constructor method to initialize values
    public Car(String carColor, String carModel) {
        color = carColor;
        model = carModel;
    }

    // Method to display information about the car
    public void displayInfo() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
    }
}

Explanation:

  • Here, we define a class Car with two fields: color and model.
  • A constructor Car(String carColor, String carModel) is provided to initialize these fields.
  • A method displayInfo() is used to print out the details of the Car.

2. Creating an Object of the Class

Now let's create an object of our Car class.

Example Code:

// Define the main class
public class Main {
    public static void main(String[] args) {
        // Create an object of Car
        Car myCar = new Car("Red", "Toyota Corolla");

        // Call displayInfo method on the Car object
        myCar.displayInfo();
    }
}

Explanation:

  • We create an object of the Car class called myCar. The object is initialized using the constructor method with the arguments "Red" and "Toyota Corolla".
  • We then call the displayInfo() method on myCar to print its attributes.

3. Adding Methods to the Class

Methods are used to perform specific activities or functions. Let’s enhance our Car class.

Example Code:

public class Car {
    String color;
    String model;
    int year;

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

    // Method to display information about the car
    public void displayInfo() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }

    // Method to change the color of the car
    public void repaint(String newColor) {
        color = newColor;
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Red", "Toyota Corolla", 2021);  
        myCar.displayInfo();  // Output before repainting

        myCar.repaint("Blue");  // Change the color
        myCar.displayInfo();  // Output after repainting
    }
}

Explanation:

  • A new field year has been added to our Car class.
  • The constructor now accepts three parameters for initialization.
  • Another method repaint(String newColor) is introduced to modify the color attribute.

4. Access Modifiers

Access modifiers control the visibility of classes, fields, methods, and constructors. Common access modifiers are:

  • public: can be accessed from anywhere.
  • private: can only be accessed within its own class.
  • If no modifier is specified, it becomes default, which means accessible within the same package.

Let's create a class with private fields and public methods to manipulate them.

Example Code:

public class Car {
    // Private fields
    private String color;
    private String model;
    private int year;

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

    // Getter for color field
    public String getColor() {
        return color;
    }

    // Setter for color field
    public void setColor(String newColor) {
        color = newColor;
    }

    // Method to display information about the car
    public void displayInfo() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Red", "Toyota Corolla", 2021);
        myCar.displayInfo();  // Display initial info

        // Repaint the car using setter method
        myCar.setColor("Blue");
        System.out.println("Updated Color: " + myCar.getColor());

        myCar.displayInfo();  // Display updated info
    }
}

Explanation:

  • Fields color, model and year are declared as private inside Car class.
  • Public getter and setter methods provide controlled access to the fields.
  • In Main class, we use setter and getter to change and retrieve the color.

5. Static Variables and Methods

Static members belong to the class rather than any specific instance.

Example Code:

public class Car {
    // Non-static fields
    String color;
    String model;
    int year;

    // Static variable shared among all instances
    private static int numberOfCars = 0;

    // Constructor method with counter increment
    public Car(String color, String model, int year) {
        this.color = color;
        this.model = model;
        this.year = year;
        numberOfCars++;  // Increment count each time a Car is created
    }

    // Non-static method to display information about the car
    public void displayInfo() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }

    // Static method to display the number of cars created
    public static void displayTotalCars() {
        System.out.println("Total Cars Created = " + numberOfCars);
    }
}

public class Main {
    public static void main(String[] args) {
        // Create three Car objects
        Car car1 = new Car("Red", "Toyota Corolla", 2021);
        Car car2 = new Car("Black", "Honda Accord", 2022);
        Car car3 = new Car("White", "Ford Fiesta", 2023);

        car1.displayInfo();  // Display car1 attributes
        Car.displayTotalCars();  // Display the total cars created so far
    }
}

Explanation:

  • numberOfCars is a static variable shared across all instances of Car.
  • Every time a new Car object is created, numberOfCars is incremented.
  • The static method displayTotalCars() provides a way to check the total count of Car instances.

6. Inheritance

Inheritance allows a class to inherit fields and methods from another class.

Example Code:

// Superclass
public class Vehicle {
    protected String make; // Accessible to subclasses and classes within the same package

    public Vehicle(String make) {
        this.make = make;
    }

    public void startEngine() {
        System.out.println(make + "'s engine started.");
    }
}

// Subclass extending Vehicle
public class Car extends Vehicle {
    private String color;
    private String model;

    public Car(String make, String color, String model) {
        super(make); // Call the superclass constructor
        this.color = color;
        this.model = model;
    }

    // Override superclass method
    @Override
    public void startEngine() {
        System.out.println(make + " " + model + "'s engine started with a Vroom!");
    }

    public void displayDetails() {
        System.out.println("Car Make: " + make);
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle("Toyota");
        vehicle.startEngine();  // Start Toyota engine

        Car car = new Car("Honda", "Black", "Accord");
        car.startEngine();  // Start Honda Accord engine
        car.displayDetails();  // Display Honda Accord details
    }
}

Explanation:

  • Vehicle class is the superclass which contains common attributes like make and methods like startEngine().
  • Car class inherits from Vehicle. It uses super(make) to call the superclass constructor.
  • Car class overrides startEngine() to provide a specific implementation for cars.
  • displayDetails() demonstrates how to access the inherited make field.

7. Polymorphism

Polymorphism allows methods to do different things based on object it is acting upon. Method overriding and method overloading are key concepts of polymorphism.

Example Code:

// Superclass
public class Animal {
    // Method to show what the animal does
    public void speak() {
        System.out.println("Animal speaks");
    }
}

// Subclasses inheriting from Animal
public class Dog extends Animal {
    // Overriding the speak method
    @Override
    public void speak() {
        System.out.println("Dog barks");
    }
}

public class Cat extends Animal {
    // Overriding the speak method
    @Override
    public void speak() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create objects of Dog and Cat
        Dog dog = new Dog();
        Cat cat = new Cat();

        // Use polymorphism to call the overridden speak methods
        dog.speak();  // Outputs "Dog barks"
        cat.speak();  // Outputs "Cat meows"

        // Create an array of Animals and populate it with Dog and Cat objects
        Animal[] animals = new Animal[2];
        animals[0] = new Dog();
        animals[1] = new Cat();

        // Loop through the array and call speak
        for(Animal animal : animals) {
            animal.speak();  // Correct method is called for each object
        }
    }
}

Explanation:

  • Animal has a method speak() which is overridden in Dog and Cat.
  • When calling speak() through dog or cat reference, the respective subclass method is executed (polymorphism).
  • An array of Animal type can hold objects of Dog or Cat due to polymorphism.

Summary

  • Classes and Objects: A class defines the blueprint for an object, and objects are instances of a class.
  • Fields: Variables defined inside a class.
  • Constructor: Special method used to initialize objects.
  • Methods: Blocks of code that execute certain tasks, defined inside a class.
  • Access Modifiers: Control the visibility of class members.
  • Static Members: Shared among all objects of a class.
  • Inheritance: A class can inherit methods and fields from a base (super) class.
  • Polymorphism: Methods have multiple forms, allowing for more flexible use.

Top 10 Interview Questions & Answers on Java Programming Classes and Objects

1. What is a Class in Java?

Answer: A class in Java is a blueprint or template from which objects are created. It encapsulates data for the object (attributes) and methods that define behaviors of the object. In essence, a class represents a real-world entity like a car, book, or a person.

Example:

public class Car {
    String brand;
    int year;

    public void startEngine() {
        System.out.println("Engine started.");
    }
}

In the above example, Car is a class.

2. What is an Object in Java?

Answer: An object is an instance of a class. It is a concrete entity based on the class blueprint containing actual values instead of variables. You can create multiple objects from a single class.

Example:

// Creating an object of Car class named 'myCar'
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2023;

3. How do you define a Constructor in Java?

Answer: A constructor in Java is a special method used for initializing newly created objects. Constructors have the same name as the class and no explicit return type (not even void).

Default Constructor:

public class Person {
    String name;
    int age;

    // Default constructor
    public Person() {
        name = "Unknown";
        age = 0;
    }
}

Parameterized Constructor:

public class Person {
    String name;
    int age;

    // Parameterized constructor
    public Person(String n, int a) {
        name = n;
        age = a;
    }
}

4. What does it mean when we say Java supports Encapsulation?

Answer: Encapsulation is one of the core principles of object-oriented programming. It means bundling the attributes (fields) and behaviors (methods) of an object together as a single unit and hiding the internal state of the object from other classes. This is achieved using private access modifiers for fields and providing public getter/setter methods to access them.

Example:

public class Circle {
    private double radius; // Private field

    // Public method to get the radius
    public double getRadius() { 
        return radius; 
    }

    // Public method to set the radius
    public void setRadius(double r) {
        if (r > 0)
            this.radius = r; 
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

5. What is Inheritance in Java?

Answer: Inheritance allows a class to inherit (reuse) the properties and methods of another class, referred to as the superclass or parent class. The class that inherits these properties is known as the subclass or derived class.

Basic Syntax:

class Animal {
    public void eat() {
        System.out.println("Eating...");
    }
}

// Inheriting Animal class in Dog
class Dog extends Animal {
    public void bark() {
        System.out.println("Barking...");
    }
}

In this example, Dog inherits eat method from Animal.

6. How does Polymorphism differ from Overriding in Java?

Answer: Polymorphism is the ability of an object to take on many forms, allowing objects to be treated as instances of their parent class rather than their actual class. There are two types of polymorphism: compile-time (method overloading) and runtime (method overriding).

Method Overriding: When a subclass has a method with the same name, return type, and parameters as a method in its superclass. The overridden method gets preference during the method call if the object is an instance of the subclass.

Example:

class Animal {
    public void makeSound() {
        System.out.println("Some generic animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark

7. Explain the concept of Method Overloading in Java with an Example.

Answer: Method overloading occurs when multiple methods within the same class have the same name but different parameters (number of parameters, parameter type, or both). The correct method to invoke is determined at compile time based on the provided arguments.

Example:

public class Calculator {
    // Method to add two integers
    public int add(int num1, int num2) {
        return num1 + num2;
    }

    // Method to add three integers
    public int add(int num1, int num2, int num3) {
        return num1 + num2 + num3;
    }

    // Method to concatenate two strings
    public String add(String str1, String str2) {
        return str1 + str2;
    }
}

You can call different add methods based on your argument types and number.

8. What is Access Modifiers in Java? Give examples.

Answer: Access modifiers in Java control the visibility of classes, fields, methods, and constructors. The four main access modifiers are:

  • public: accessible by all classes.
  • protected: accessible within the same package and subclasses.
  • default: accessible only within the same package (package-private).
  • private: accessible only within the declared class.

Examples:

public class BankAccount {
    private double balance; // Private attribute accessible only inside BankAccount class

    public void deposit(double amount) { // Public method
        if (amount > 0)
            balance += amount;
    }

    protected double getBalance() { // Protected method
        return balance;
    }
}

9. Define an Abstract Class and Interface in Java with Examples.

Answer: Both abstract classes and interfaces are used to achieve abstraction in Java, but they serve slightly different purposes.

Abstract Class: A class that cannot be instantiated on its own and may contain abstract methods without implementation (must be implemented by subclasses) as well as non-abstract methods with implementations.

Example:

abstract class Shape {
    abstract void draw(); // Abstract method

    void display() { // Non-abstract method
        System.out.println("Display shape details...");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle...");
    }
}

Interface in Java: Similar to abstract classes except that interfaces can only contain method declarations (from Java 8 onwards, default and static methods can also be defined) and constants (fields). Classes that implement interfaces must provide implementations for all abstract methods.

Example:

interface Animal {
    void eat(); // Abstract method

    // Default method (Java 8+)
    default void sleep() {
        System.out.println("Sleeping...");
    }
}

class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("Dog eats bones...");
    }

    // Not mandatory to redefine sleep(), as it has a default definition
}

10. What is a Static Member in Java? Provide Examples.

Answer: Static members belong to the class rather than any specific object of the class. Therefore, they can be accessed without creating an instance of the class. Both static variables and static methods are declared using the static keyword.

Static Variables:

public class Counter {
    static int count = 0; // Static variable shared among all instances of Counter

    public void increment() {
        count++;
    }

    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();

        c1.increment();
        c2.increment();
        System.out.println("Total increments: " + Counter.count); // Outputs: Total increments: 2
    }
}

Static Methods:

You May Like This Related .NET Topic

Login to post a comment.