Insights into Company
← Java

Class

Understand the idea. Compare it. Explain it. Test yourself.

Question 1 of 12

What is a class in Java?

Solution and explanation

What it is

A class is a blueprint or template that describes what an object will contain (fields/state) and what it can do (methods/behaviour). The class itself is just a definition; objects are the real instances created from it.

Analogy: the architect's plan of a flat is the class. The 200 flats built from that plan in a society are objects. Every flat has the same structure (rooms, doors) but different values (owner name, paint colour).

Structure of a class

public class Car {                       // class declaration
    // 1. Fields (state)
    private String brand;
    private String model;
    private int speed;

    // 2. Constructor (initialises a new object)
    public Car(String brand, String model) {
        this.brand = brand;
        this.model = model;
    }

    // 3. Methods (behaviour)
    public void accelerate(int amount) {
        speed += amount;
    }

    public String describe() {
        return brand + " " + model + " at " + speed + " km/h";
    }
}

Using the class

Car baleno = new Car("Maruti", "Baleno");
Car creta  = new Car("Hyundai", "Creta");
baleno.accelerate(60);
System.out.println(baleno.describe());   // Maruti Baleno at 60 km/h
System.out.println(creta.describe());    // Hyundai Creta at 0 km/h

What a class can contain

  • Fields (instance and static variables)
  • Constructors
  • Methods (instance and static)
  • Blocks (instance initializer { }, static block static { })
  • Nested classes, interfaces, enums and records

Rules

  • A .java file can have only one public top-level class, and the file name must match it (Car.java).
  • Class names use PascalCase by convention.
  • Every class implicitly extends java.lang.Object.
Practice explaining this
Question 2 of 12

Why do we need a class?

Solution and explanation

The problem without classes

Imagine storing 1,000 employees using separate variables or parallel arrays:

String[] names = new String[1000];
double[] salaries = new double[1000];
String[] departments = new String[1000];
// Easy to get out of sync: names[5] must always match salaries[5]

Data and the logic that works on it are scattered, nothing stops invalid values (negative salary), and every new attribute means another array.

The class solution

public class Employee {
    private final String name;
    private double salary;
    private String department;

    public Employee(String name, double salary, String department) {
        if (salary < 0) throw new IllegalArgumentException("Salary cannot be negative");
        this.name = name;
        this.salary = salary;
        this.department = department;
    }

    public void giveRaise(double percent) {
        salary += salary * percent / 100;
    }

    public double getSalary() { return salary; }
}

List<Employee> staff = new ArrayList<>();
staff.add(new Employee("Asha", 60000, "IT"));

Why classes are needed

  1. Grouping: related data and behaviour live together (an Employee knows how to give itself a raise).
  2. Reusability: write the blueprint once, create thousands of objects.
  3. Encapsulation: private fields plus validation keep objects in a valid state.
  4. Abstraction: callers use giveRaise(10) without knowing how it is calculated.
  5. Inheritance and polymorphism: Manager extends Employee reuses code and can override behaviour.
  6. Modelling the real world: Order, Customer, Invoice map naturally to business concepts, which makes large codebases understandable.
  7. Java requires it: every method and variable must live inside a class (or interface/enum/record).
Practice explaining this
Question 3 of 12

What is the difference between a class and an object?

Solution and explanation

Short answer

A class is the blueprint; an object is a real thing built from that blueprint, occupying memory and holding its own values.

ClassObject
Logical template / definitionPhysical instance in memory
Declared once with the class keywordCreated many times with new
No memory for instance fields when declaredHeap memory allocated for its fields
Example: StudentExample: rahul, priya
Loaded once by the class loaderEach has its own state

Example

class Student {               // class: one definition
    String name;
    int rollNo;
}

Student rahul = new Student();   // object 1
rahul.name = "Rahul"; rahul.rollNo = 1;

Student priya = new Student();   // object 2
priya.name = "Priya"; priya.rollNo = 2;
Method area: class Student (fields: name, rollNo)
Heap:  [Student@1a2b: name="Rahul", rollNo=1]   ← rahul
       [Student@3c4d: name="Priya", rollNo=2]   ← priya

Analogy: "Smartphone model iPhone 16" is the class; the phone in your pocket with your photos and IMEI number is an object.

Practice explaining this
Question 4 of 12

Can a Java class exist without creating an object?

Solution and explanation

Answer

Yes. A class is loaded and usable without any instance being created. You can use its static members, and some classes are designed never to be instantiated.

1. Using static members

public class MathUtils {
    public static final double GST = 0.18;

    public static double withGst(double amount) {
        return amount * (1 + GST);
    }
}

System.out.println(MathUtils.withGst(1000));   // 1180.0 — no object created

The JDK does the same: Math.max(3, 7), Integer.parseInt("42"), Collections.sort(list).

2. Utility classes that forbid objects

public final class StringUtils {
    private StringUtils() { }          // private constructor: no one can call new StringUtils()
    public static boolean isBlank(String s) { return s == null || s.isBlank(); }
}

3. Abstract classes and interfaces

An abstract class cannot be instantiated directly, but it exists, can have static methods and is used through subclasses.

4. The main class

public static void main(String[] args) runs without creating an object of the class that contains it; that is why main is static.

When does the class load?

The JVM loads and initialises a class the first time it is actively used: creating an object, calling a static method, or accessing a non-constant static field. Static blocks run at that moment, even if no object is ever created.

Practice explaining this
Question 5 of 12

What are instance variables?

Solution and explanation

What they are

Instance variables are non-static fields declared inside a class but outside any method. Every object gets its own separate copy, stored inside that object on the heap.

public class BankAccount {
    private String holder;        // instance variable
    private double balance;       // instance variable

    public BankAccount(String holder) { this.holder = holder; }
    public void deposit(double amt) { balance += amt; }
}

BankAccount a = new BankAccount("Ravi");
BankAccount b = new BankAccount("Meena");
a.deposit(500);
// a.balance = 500.0, b.balance = 0.0 — separate copies

Characteristics

  • Created when the object is created with new, destroyed when the object is garbage collected.
  • Get default values if not initialised: 0 for numbers, false for boolean, '\u0000' for char, null for references. (Local variables get no default and must be assigned before use.)
  • Can have any access modifier; usually private (encapsulation).
  • Accessed through an object reference (a.balance) or this.balance inside the class.
  • Cannot be used directly from a static method, because a static method has no this object.
Instance variableStatic (class) variableLocal variable
DeclaredIn class, no staticIn class, with staticInside a method/block
CopiesOne per objectOne per classOne per method call
MemoryHeap (inside object)Method area / metaspaceStack
Default valueYesYesNo
Practice explaining this
Question 6 of 12

What are instance methods?

Solution and explanation

What they are

Instance methods are non-static methods that operate on a particular object. They are called on an object reference and have access to that object's instance variables through the implicit this reference.

public class Cart {
    private final List<Double> prices = new ArrayList<>();

    public void add(double price) {          // instance method: changes this cart's state
        prices.add(price);
    }

    public double total() {                  // instance method: reads this cart's state
        return prices.stream().mapToDouble(Double::doubleValue).sum();
    }
}

Cart myCart = new Cart();
myCart.add(499);
myCart.add(1299);
System.out.println(myCart.total());   // 1798.0

Key points

  • Need an object: myCart.total(); calling Cart.total() does not compile.
  • Can access both instance and static members of the class.
  • Support overriding: a subclass can replace an instance method, and the JVM chooses the version at run time based on the actual object (dynamic dispatch). This is the basis of polymorphism.
  • Behind the scenes the object is passed as a hidden parameter this.

Types by purpose

  • Accessors (getters): return state without changing it.
  • Mutators (setters or business actions): change state, ideally with validation.
  • Behaviour methods: order.place(), account.withdraw(500).
Practice explaining this
Question 7 of 12

What are class variables?

Solution and explanation

What they are

Class variables are fields declared with static. There is exactly one copy per class, shared by all objects of that class, and it exists even if no object is created.

public class Employee {
    private static int count = 0;              // class variable: shared
    public static final String COMPANY = "Infosys";  // constant
    private final int id;                       // instance variable

    public Employee() {
        count++;
        id = count;                             // each employee gets the next id
    }

    public static int getCount() { return count; }
}

new Employee(); new Employee(); new Employee();
System.out.println(Employee.getCount());   // 3
Class Employee (metaspace/static area): count = 3, COMPANY = "Infosys"
Heap: Employee{id=1}  Employee{id=2}  Employee{id=3}

When to use

  • Counters and id generators shared across objects.
  • Constants: static final (e.g. MAX_RETRIES = 3).
  • Shared caches or configuration (with care for thread safety).

Cautions

  • Mutable static state is shared by all threads; protect it (AtomicInteger, synchronization).
  • Access through the class name (Employee.count), not an object, to make it clear the value is shared.
Practice explaining this
Question 8 of 12

What is a nested class?

Solution and explanation

What it is

A nested class is a class declared inside another class. It groups classes that are only used together, increases encapsulation and can make code more readable.

Four kinds

public class Outer {
    private int x = 10;
    private static int y = 20;

    static class StaticNested {               // 1. static nested class
        void show() { System.out.println(y); }        // can access only static members of Outer directly
    }

    class Inner {                             // 2. inner (non-static) class
        void show() { System.out.println(x + y); }    // can access everything, including private x
    }

    void method() {
        class Local {                         // 3. local class (inside a method)
            void show() { System.out.println(x); }
        }
        new Local().show();

        Runnable r = new Runnable() {         // 4. anonymous class
            public void run() { System.out.println("anonymous " + x); }
        };
        r.run();
    }
}

Creating objects

Outer.StaticNested a = new Outer.StaticNested();   // no Outer object needed
Outer outer = new Outer();
Outer.Inner b = outer.new Inner();                 // needs an Outer object
KindNeeds outer objectAccess to outer instance fields
Static nestedNoNo (only via an explicit reference)
InnerYesYes
LocalYes (in instance methods)Yes, plus effectively final locals
AnonymousSame as localSame as local

Real use: Map.Entry is a nested interface of Map; a Builder is usually a static nested class (Pizza.Builder).

Practice explaining this
Question 9 of 12

What is an inner class?

Solution and explanation

What it is

An inner class is a non-static nested class. Each inner-class object is tied to an object of the outer class and can access all its members, including private ones.

public class Bank {
    private final String name = "SBI";
    private double interestRate = 6.5;

    public class Account {                        // inner class
        private double balance;

        public Account(double balance) { this.balance = balance; }

        public double yearlyInterest() {
            return balance * interestRate / 100;  // uses the outer object's private field
        }

        public String bankName() {
            return Bank.this.name;                // explicit reference to the outer object
        }
    }
}

Bank sbi = new Bank();
Bank.Account acc = sbi.new Account(100000);
System.out.println(acc.yearlyInterest());   // 6500.0

How it works

The compiler adds a hidden field in the inner object pointing to its outer object (Bank.this). That is why an outer object is required to create it.

Points to remember

  • Before Java 16 an inner class could not declare static members (except constants); since Java 16 it can.
  • Because it holds a reference to the outer object, an inner object keeps the outer object alive. In Android/long-lived code this can cause memory leaks; prefer a static nested class if the outer instance is not needed.
  • Use when the inner object logically cannot exist without the outer one, e.g. an iterator over a custom collection.
Practice explaining this
Question 10 of 12

What is an anonymous class?

Solution and explanation

What it is

An anonymous class is a class without a name, declared and instantiated in a single expression. It either extends a class or implements an interface, and is used for one-off implementations.

interface Discount {
    double apply(double price);
}

Discount festive = new Discount() {          // anonymous class implementing Discount
    @Override
    public double apply(double price) {
        return price * 0.8;                  // 20% off
    }
};
System.out.println(festive.apply(1000));     // 800.0

Extending a class anonymously

Thread t = new Thread() {
    @Override public void run() { System.out.println("Running in " + getName()); }
};
t.start();

Anonymous class vs lambda

Since Java 8, functional interfaces (one abstract method) are usually written as lambdas:

Discount festive = price -> price * 0.8;
Comparator<String> byLength = (a, b) -> a.length() - b.length();
Anonymous classLambda
Can implement interfaces with many methods or extend classesOnly functional interfaces
Can have fields and stateNo own state
this refers to the anonymous objectthis refers to the enclosing object
Generates a separate .class file (Outer$1.class)Uses invokedynamic, no extra class file

Rules

  • Cannot have a constructor (no name), but can use an instance initializer block.
  • Can access effectively final local variables of the enclosing method.
Practice explaining this

Showing questions 1–10 of 12