Java Classes and Objects


Java Classes and Objects Interview with follow-up questions

1. What is a class in Java?

A class is a blueprint/template that defines the state (fields) and behavior (methods) shared by objects of that type. It's also a namespace for constructors, nested types, and static members. You create objects (instances) from it with new.

public class Car {
    private String model;              // state (field)
    Car(String model) { this.model = model; }   // constructor
    void drive() { System.out.println(model + " driving"); }  // behavior
}

Key elements interviewers expect: fields, methods, constructors (initialize new objects), access modifiers (public/private/…), and optionally static members (class-level) and nested classes. A class defines a type and supports encapsulation, inheritance, and polymorphism.

A current note that signals up-to-date knowledge: Java now has specialized class forms — record (Java 16+) for concise, immutable data carriers (auto-generates constructor, accessors, equals/hashCode/toString), enum for fixed instances, and sealed classes (Java 17+) to restrict which classes may extend them. So while the "blueprint for objects" definition is correct, mentioning records/sealed classes shows you know how modern Java models data and hierarchies.

↑ Back to top

Follow-up 1

What are the different components of a class?

A class in Java consists of the following components:

  1. Class declaration: It includes the class name and any optional modifiers.
  2. Fields: These are variables that represent the state or data of the class.
  3. Methods: These are functions that define the behavior of the class.
  4. Constructors: These are special methods used for initializing objects of the class.
  5. Inner classes: These are classes defined within another class.
  6. Static initializer blocks: These are blocks of code that are executed when the class is loaded.
  7. Instance initializer blocks: These are blocks of code that are executed when an instance of the class is created.

Follow-up 2

How does a class differ from an object in Java?

In Java, a class is a blueprint or a template for creating objects, whereas an object is an instance of a class. A class defines the properties and behaviors that an object will have, while an object represents a specific instance of a class with its own unique state and behavior. Multiple objects can be created from a single class, each with its own separate data and behavior.

Follow-up 3

Can you provide an example of a class in Java?

Sure! Here's an example of a simple class in Java:

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

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

    // Methods
    public void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
}

In this example, the Person class has two fields (name and age), a constructor that takes name and age as parameters, and a sayHello() method that prints a greeting message with the person's name and age.

Follow-up 4

What is the purpose of a class constructor?

A class constructor in Java is a special method that is used for initializing objects of the class. It is called automatically when an object is created using the new keyword. The purpose of a constructor is to set the initial state of an object by assigning values to its fields or performing any other necessary initialization tasks. Constructors can take parameters to initialize the object with specific values, or they can be parameterless. If a class does not define any constructors, a default constructor (with no parameters) is automatically provided by the Java compiler.

2. What is an object in Java?

An object is a concrete instance of a class — a runtime entity that has its own state (the values of its fields) and behavior (the methods it can run). Where the class is the blueprint, the object is the actual thing built from it, living on the heap and referenced by a variable.

Car c1 = new Car("Tesla");   // c1 references a Car object
Car c2 = new Car("BMW");     // a separate object with its own state

Points interviewers like: objects are created with new (which allocates heap memory and runs a constructor), each has its own copy of instance fields, and variables hold references to objects (not the objects themselves) — which is why == compares references and assignment copies the reference, not the object. Objects are reclaimed automatically by the garbage collector when no longer reachable (no manual delete).

A current note: not everything is created with new anymore — records and factory methods (List.of(...), Optional.of(...)) are common ways to obtain objects, and value-like data is often modeled as immutable objects/records. The core idea stands: an object is a class instance with identity, state, and behavior.

↑ Back to top

Follow-up 1

How is an object created in Java?

An object is created in Java by using the 'new' keyword followed by the constructor of the class. The 'new' keyword allocates memory for the object and initializes its instance variables.

Follow-up 2

Can you provide an example of object creation in Java?

Sure! Here's an example of creating an object of class 'Person':

Person person = new Person();

Follow-up 3

What is the 'new' keyword in Java?

In Java, the 'new' keyword is used to create an instance of a class. It dynamically allocates memory for the object and returns a reference to it.

Follow-up 4

What is the purpose of the 'this' keyword in Java?

The 'this' keyword in Java is a reference to the current object. It is used to refer to the instance variables and methods of the current object. It is often used to disambiguate between instance variables and local variables with the same name.

3. What is the difference between a class and an object in Java?

A class is the definition/blueprint — a compile-time construct describing what fields and methods instances will have. An object is a runtime instance of that class, with its own state, created with new.

class Car { String model; }        // the class (one definition)
Car a = new Car();                 // object #1 (its own state)
Car b = new Car();                 // object #2 (separate state)

The distinctions interviewers want:

  • One class, many objects — the class is declared once; you can create unlimited instances, each with independent field values.
  • Memory — a class definition is metadata (loaded once into the method area/metaspace); each object occupies its own space on the heap.
  • Lifetime — a class is loaded by a class loader and stays; objects are created on demand and garbage-collected when unreachable.
  • Identity — distinct objects have distinct identities even with equal field values (== is false unless they're the same instance).

A neat analogy: the class is the recipe, objects are the cakes baked from it. Modern note: some types blur this — a record is still a class producing objects, and enum instances are a fixed set of objects created once — but the class-vs-object distinction (definition vs instance) holds throughout.

↑ Back to top

Follow-up 1

How does the concept of class and object relate to the real world?

The concept of class and object in Java can be related to real-world objects and their characteristics. For example, consider the class 'Car'. The class defines the properties of a car such as color, speed, and behavior such as accelerating. An object of the 'Car' class represents a specific car with its own color, speed, and can perform actions like accelerating.

Follow-up 2

What is the relationship between class variables and instance variables?

In Java, class variables (also known as static variables) are shared among all instances of a class. They are declared using the 'static' keyword and are accessed using the class name. Instance variables, on the other hand, are unique to each instance of a class. They are declared without the 'static' keyword and are accessed using the instance name. Class variables are useful for storing data that is common to all instances of a class, while instance variables store data that is specific to each instance.

Follow-up 3

Can you provide an example to illustrate the difference?

Sure! Here's an example:

public class Car {
    String color;
    int speed;

    public void accelerate() {
        speed += 10;
    }
}

Car myCar = new Car();
myCar.color = "red";
myCar.speed = 50;
myCar.accelerate();

4. What is the concept of 'Inheritance' in Java?

Inheritance lets a class acquire the fields and methods of another class, modeling an "is-a" relationship and enabling code reuse and polymorphism. The class that inherits is the subclass (extends keyword); the one inherited from is the superclass.

class Animal { void eat() { ... } }
class Dog extends Animal {           // Dog is-an Animal
    void bark() { ... }
}
new Dog().eat();   // inherited from Animal

Points interviewers expect: a subclass can add members and override inherited methods (runtime polymorphism); super accesses the parent's members/constructor; every class implicitly extends Object; and Java allows single class inheritance but multiple interface inheritance (a class can implement many interfaces). Constructors are not inherited, and a subclass constructor implicitly calls super() first.

The crucial modern caveat: prefer composition over inheritance. Deep inheritance hierarchies are brittle ("fragile base class"), so favor has-a composition and interfaces unless there's a genuine is-a relationship. Java reinforces this with sealed classes (Java 17+), which let a superclass permit only specific subclasses — giving controlled, exhaustive hierarchies that pair well with pattern matching. So: inheritance is fundamental, but use it deliberately and lean on composition/interfaces by default.

↑ Back to top

Follow-up 1

How is inheritance implemented in Java?

In Java, inheritance is implemented using the 'extends' keyword. To create a subclass that inherits from a superclass, the 'extends' keyword is used in the class declaration. For example:

public class Subclass extends Superclass {
    // subclass code
}

Follow-up 2

Can you provide an example of inheritance in Java?

Sure! Here's an example of inheritance in Java:

public class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println("The dog is barking.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Output: The animal is eating.
        dog.bark(); // Output: The dog is barking.
    }
}

Follow-up 3

What is the 'super' keyword in Java?

In Java, the 'super' keyword is used to refer to the superclass of a subclass. It can be used to call the superclass constructor, access superclass methods and variables, and invoke the superclass implementation of an overridden method. The 'super' keyword is often used in the context of inheritance to differentiate between superclass and subclass members with the same name.

Follow-up 4

What is the difference between single and multiple inheritance?

In single inheritance, a class can inherit from only one superclass. This means that a subclass can have only one direct superclass. On the other hand, in multiple inheritance, a class can inherit from multiple superclasses. This allows a subclass to have multiple direct superclasses.

Java supports single inheritance, where a class can extend only one superclass. However, Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces.

5. What is 'Polymorphism' in Java?

Polymorphism ("many forms") lets the same interface/reference operate on different underlying types, with the right behavior chosen for the actual object. Java has two kinds:

  • Compile-time (static) polymorphismmethod overloading; the compiler picks the method from the argument types.
  • Runtime (dynamic) polymorphismmethod overriding; a superclass/interface reference points to a subclass object, and the JVM dispatches to the object's actual method at runtime.
List list = new ArrayList<>();   // program to the interface
Animal a = new Dog();
a.sound();   // calls Dog's overridden sound() — decided at runtime

Why it matters: it enables writing code against a general type (an interface or base class) while behavior varies by concrete type — the foundation of extensible, loosely-coupled design (e.g. List backed by ArrayList or LinkedList; a Comparator parameter accepting any comparison).

A current note: modern Java complements classic subtype polymorphism with pattern matching for switch over sealed hierarchies — instead of overriding a method per subtype, you can branch on type exhaustively and safely:

String describe(Shape s) {
    return switch (s) {                 // sealed Shape: Circle, Square
        case Circle c -> "circle";
        case Square sq -> "square";
    };
}

So polymorphism today spans overriding/overloading and pattern matching — knowing both is what signals current Java fluency.

↑ Back to top

Follow-up 1

What is the difference between static and dynamic polymorphism?

Static polymorphism, also known as compile-time polymorphism, is achieved through method overloading. It allows multiple methods with the same name but different parameters to be defined in a class. The appropriate method is selected based on the number and types of arguments passed during compile-time.

Dynamic polymorphism, also known as runtime polymorphism, is achieved through method overriding. It allows a subclass to provide a specific implementation of a method that is already defined in its superclass. The appropriate method is selected based on the actual type of the object at runtime.

Follow-up 2

Can you provide an example of polymorphism in Java?

Sure! Here's an example:

class Animal {
    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}

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

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat is meowing");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.makeSound(); // Output: Dog is barking
        animal2.makeSound(); // Output: Cat is meowing
    }
}

In this example, the Animal class has a makeSound() method. The Dog and Cat classes extend the Animal class and override the makeSound() method with their own implementations. When we create objects of Dog and Cat and call the makeSound() method, the appropriate implementation based on the actual type of the object is executed.

Follow-up 3

How does polymorphism enhance the flexibility of a program?

Polymorphism enhances the flexibility of a program by allowing objects to be used interchangeably, even if they belong to different classes that are related through inheritance. This means that a method can be written to accept a superclass object as a parameter, and it can also accept any of its subclasses as arguments. This makes the code more flexible and reusable, as it can work with different types of objects without needing to know their specific types.

Follow-up 4

What is the role of method overriding in polymorphism?

Method overriding is a key feature of polymorphism in Java. It allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When a method is called on an object, the JVM determines the actual type of the object at runtime and executes the appropriate method implementation. This allows different objects of related classes to have different behaviors for the same method, based on their specific implementations.

6. What is the contract between equals() and hashCode() in Java?

One of the most common Java interview questions. The rule: if two objects are equal by equals(), they must have the same hashCode() (the reverse isn't required — unequal objects may share a hash code, a collision). Consequences of the full contract: hashCode() must be consistent across calls, and equals() must be reflexive, symmetric, transitive, and consistent.

Why it matters: hash-based collections (HashMap, HashSet) rely on it. They locate an entry by hashCode() (which bucket) and then confirm with equals(). If you override equals() but not hashCode(), equal objects can land in different buckets, so map.get(key)/set.contains(x) fail to find entries — a classic bug.

record Point(int x, int y) {}   // record auto-generates equals/hashCode correctly
// or override BOTH together:
@Override public boolean equals(Object o) { ... }
@Override public int hashCode() { return Objects.hash(x, y); }

Best practices: always override both together, use Objects.equals/Objects.hash, base them on the same fields (ideally immutable ones), and prefer a record for value types since it implements both correctly for free. Interviewers love asking "what happens if you override equals but not hashCode?" — the answer is broken lookups in hash collections.

↑ Back to top

7. What is a record in Java and when should you use one?

A record (finalized in Java 16) is a concise way to declare an immutable data carrier. From a one-line declaration, the compiler generates the private final fields, canonical constructor, accessors, and equals()/hashCode()/toString() — eliminating boilerplate:

public record Point(int x, int y) {}
// auto: constructor, x(), y(), equals, hashCode, toString — all correct

Use records for value/DTO-like types: API request/response objects, map keys, tuples, immutable domain values. You can add a compact constructor for validation, implement interfaces, and add static factory methods/instance methods:

public record Range(int lo, int hi) {
    public Range {                              // compact constructor — validation
        if (lo > hi) throw new IllegalArgumentException();
    }
}

Constraints to mention: records are implicitly final, can't extend a class (they extend Record), and their fields are final (shallow immutability — a mutable field's contents can still change, so prefer immutable components). They pair powerfully with sealed interfaces + pattern matching (record patterns, Java 21) for clean, exhaustive data modeling. Records are a top "do you know modern Java?" question.

↑ Back to top

Live mock interview

Mock interview: Java Classes and Objects

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.