Types of Classes
Inner classes, anonymous classes, abstract classes, static nested classes
- Differentiate between all types of classes in Java
- Implement inner, static nested, local, and anonymous classes
- Understand when to use abstract classes
Part of the Concept and Coding Java lecture series. These notes are fully self-contained — no prior lecture viewing is required. This chapter covers: Concrete Class, Abstract Class, Super/Subclass, Object Class, and all varieties of Nested Classes.
Table of Contents
- Overview — Types of Classes in Java
- Concrete Class
- Abstract Class
- Super Class & Sub Class
- The Object Class — Parent of All
- Nested Classes — Overview
- Static Nested Class
- Non-Static Nested Class (Inner Class)
- Member Inner Class
- Local Inner Class
- Anonymous Inner Class
- Inheritance in Nested Classes
- Access Modifiers — Full Comparison
- Mermaid Diagrams
- Quick-Reference Tables
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. Overview Types of Classes in Java
Java supports many different flavors of class, each serving a distinct design purpose. The full taxonomy is:
| Class Type | Part Covered |
|---|---|
| Concrete Class | ✅ This guide |
| Abstract Class | ✅ This guide |
| Super Class / Sub Class | ✅ This guide |
| Object Class | ✅ This guide |
| Nested Class (all 5 kinds) | ✅ This guide |
| Generic Class | Part 2 |
| POJO | Part 2 |
| Enum | Part 2 |
| Final Class | Part 2 |
| Singleton Class | Part 2 |
| Immutable Class | Part 2 |
| Wrapper Class | Part 2 |
2. Concrete Class
Overview
A concrete class is the most common, everyday type of class in Java. If you have written any Java class and created objects from it, you have already used a concrete class — even if you did not know the term.
Definition
A concrete class is any class from which you can create an instance (object) using thenewkeyword, and in which all declared methods have a complete implementation.
Key Characteristics
| Property | Detail |
|---|---|
| Can create objects? | ✅ Yes — using new |
| All methods implemented? | ✅ Yes — no abstract methods allowed |
| Can extend another class? | ✅ Yes |
| Can implement an interface? | ✅ Yes — and must implement all interface methods |
| Access modifiers allowed | public or package-private (default) only |
Real-World Analogy
Think of a concrete class like a completed blueprint. An abstract class or interface is an unfinished blueprint with gaps. A concrete class has every detail filled in — you can hand it to a builder (the JVM) and it will construct the object without needing anything else.
Syntax
1public class ClassName {2 // fields3 // methods with full implementation4}Code Examples
Example 1 Simple Concrete Class
1public class Person {2 String name;3 int age;4
5 void display() { // method has full implementation6 System.out.println("Name: " + name + ", Age: " + age);7 }8}9
10public class Main {11 public static void main(String[] args) {12 Person p = new Person(); // ✅ object created with 'new'13 p.name = "Alice";14 p.age = 30;15 p.display();16 }17}Name: Alice, Age: 30
Example 2 Concrete Class Implementing an Interface
1interface Shape {2 double area(); // no implementation — just definition3}4
5public class Rectangle implements Shape { // ← concrete class implementing Shape6 double width, height;7
8 Rectangle(double w, double h) {9 this.width = w;10 this.height = h;11 }12
13 @Override14 public double area() { // ← must provide full implementation15 return width * height;16 }17}18
19public class Main {20 public static void main(String[] args) {21 Rectangle r = new Rectangle(5, 3); // ✅ object created — Rectangle is concrete22 System.out.println("Area: " + r.area());23 }24}Area: 15.0
Shape is an interface — you cannot write new Shape(). But Rectangle implements Shape and provides all method bodies, making it concrete and fully instantiable.Class-Level Access Modifiers
Unlike variables and methods — which can be public, private, protected, or default — top-level classes (declared directly in a .java file) can only be:
| Modifier | Meaning |
|---|---|
public | Accessible from any package |
| (nothing) — default / package-private | Accessible only within the same package |
1public class OpenClass { } // accessible everywhere2class PackageClass { } // accessible only within same package3private class X { } // ❌ COMPILE ERROR for top-level class4protected class Y { } // ❌ COMPILE ERROR for top-level classprivate and protected. Top-level classes are restricted to public or package-private.3. Abstract Class
Overview
An abstract class sits between a fully implemented concrete class and a completely unimplemented interface. It lets you define some behavior while leaving other behavior for child classes to fill in.
Definition
An abstract class is a class declared with theabstractkeyword. It may contain both abstract methods (no implementation) and concrete methods (with implementation). You cannot create objects of an abstract class.
What is Abstraction?
Abstraction means hiding the internal implementation details and exposing only the features (interface) that the user needs.
Real-world analogy: When you press the brake pedal in a car, you don't need to know about hydraulic fluid, callipers, rotors, or ABS logic. You just press the pedal and the car stops. The what is exposed; the how is hidden. That's abstraction.
Two Ways to Achieve Abstraction in Java
| Method | Abstraction Level | Notes |
|---|---|---|
interface | 100% | All methods are definitions only (pre-Java 8); default/static methods added in Java 8+ |
abstract class | 0% to 100% | Can mix abstract and implemented methods |
Syntax
1abstract class ClassName {2 // concrete method — has implementation3 void concreteMethod() {4 System.out.println("I have a body.");5 }6
7 // abstract method — no body, just declaration8 abstract void abstractMethod();9}Key Rules
| Rule | Detail |
|---|---|
| Declared with | abstract keyword before class |
| Abstract methods | No body — just a signature + semicolon |
| Concrete methods | Have full implementation — allowed inside abstract class |
| Can instantiate? | ❌ No — new AbstractClass() is a compile error |
| Can store a reference? | ✅ Yes — AbstractClass ref = new ConcreteSubclass() |
| Child class must | Implement all inherited abstract methods, OR itself be declared abstract |
Code Example Abstract Class Hierarchy
1// Abstract parent class2abstract class Car {3 abstract void pressBrake(); // abstract — no implementation4 abstract void pressClutch(); // abstract — no implementation5
6 void getNumberOfWheels() { // concrete — has implementation7 System.out.println("4 wheels");8 }9}10
11// Abstract child — adds more abstraction, provides some implementation12abstract class LuxuryCar extends Car {13 abstract void pressDualBrakeSystem(); // new abstract method14
15 @Override16 void pressBrake() { // provides implementation for parent's abstract method17 System.out.println("Luxury brake applied.");18 }19 // pressClutch() is still unimplemented — child must handle it20}21
22// Concrete class — must implement ALL remaining abstract methods23class Audi extends LuxuryCar {24 @Override25 void pressDualBrakeSystem() {26 System.out.println("Dual brake system engaged.");27 }28
29 @Override30 void pressClutch() {31 System.out.println("Clutch pressed.");32 }33}34
35public class Main {36 public static void main(String[] args) {37 // Car c = new Car(); // ❌ COMPILE ERROR — abstract38 // LuxuryCar lc = new LuxuryCar(); // ❌ COMPILE ERROR — abstract39
40 Audi a = new Audi(); // ✅ concrete class — OK41 a.pressBrake();42 a.pressClutch();43 a.pressDualBrakeSystem();44 a.getNumberOfWheels();45
46 // Storing concrete object in abstract parent reference — VALID47 LuxuryCar ref = new Audi();48 ref.pressBrake();49 }50}Luxury brake applied. Clutch pressed. Dual brake system engaged. 4 wheels Luxury brake applied.
Step-by-Step Explanation
Cardeclares two abstract methods (pressBrake,pressClutch) and one concrete method (getNumberOfWheels).LuxuryCar extends Car— it is also abstract. It implementspressBrakebut leavespressClutchunimplemented, and adds a new abstract methodpressDualBrakeSystem.Audi extends LuxuryCar— it is concrete, so it must implement all remaining abstract methods:pressClutchandpressDualBrakeSystem. (pressBrakeis already covered byLuxuryCar.)- Objects of
Audican be stored in references of typeCarorLuxuryCar— this is polymorphism.
Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract class | interface |
| Abstraction level | 0–100% | 100% (default pre-Java 8) |
| Constructor | ✅ Allowed | ❌ Not allowed |
| Instance variables | ✅ Allowed | Only public static final constants |
| Access modifiers on methods | Any | public by default |
| Multiple inheritance | ❌ Only one class | ✅ A class can implement many |
extends vs implements | Extended with extends | Implemented with implements |
4. Super Class & Sub Class
Definitions
Superclass
(also called parent class or base class): The class that is being inherited from.
Subclass
(also called child class or derived class): The class that inherits from the superclass.
Syntax
1class Superclass {2 // parent content3}4
5class Subclass extends Superclass {6 // child content — inherits everything from Superclass (except private members)7}Code Example
1class A {2 void display() {3 System.out.println("I am class A — the superclass.");4 }5}6
7class B extends A { // B is a subclass of A8 void show() {9 System.out.println("I am class B — the subclass.");10 }11}12
13public class Main {14 public static void main(String[] args) {15 B obj = new B();16 obj.display(); // inherited from A17 obj.show(); // defined in B18 }19}I am class A — the superclass. I am class B — the subclass.
Key Points
- A class can have only one direct superclass in Java (no multiple class inheritance).
- A class can have multiple subclasses.
- The subclass inherits all non-private fields and methods of the superclass.
- The subclass can override (redefine) inherited methods.
5. The Object Class Parent of All
Overview
This is one of the most important concepts in all of Java and a classic interview topic.
Definition
In Java, every class that does not explicitly extend another class implicitly extendsjava.lang.Object. TheObjectclass is therefore the ultimate parent of every class in Java.
The Implicit Hierarchy
When you write:
1class Person {2 // no 'extends' keyword3}Java treats it exactly as:
1class Person extends Object {2 // 'extends Object' is implicit3}Visual Hierarchy
Every class, no matter how deeply nested in an inheritance chain, traces its ancestry back to Object.
Important Methods Provided by Object
The Object class gives every Java class access to these built-in methods:
| Method | Description |
|---|---|
toString() | Returns a string representation of the object |
equals(Object obj) | Checks if two objects are logically equal |
hashCode() | Returns an integer hash code for the object |
getClass() | Returns the runtime Class of the object |
clone() | Creates and returns a copy of the object |
wait() | Used in multi-threading — causes thread to wait |
notify() | Used in multi-threading — wakes one waiting thread |
notifyAll() | Wakes all threads waiting on this object |
finalize() | Called by GC before object is garbage collected (deprecated in Java 9+) |
wait(), notify(), and notifyAll() will be covered in detail in the Concurrency / Threading section.Code Example Using Object as Universal Reference
1class Person { }2class Audi { }3
4public class ObjectTest {5 public static void main(String[] args) {6 // Object is parent of all — any object can be stored in Object reference7 Object obj1 = new Person();8 Object obj2 = new Audi();9
10 // getClass() — find out what actual type is stored11 System.out.println(obj1.getClass()); // Output: class Person12 System.out.println(obj2.getClass()); // Output: class Audi13 }14}class Person class Audi
When Is This Useful?
When you write a utility method or data structure that needs to accept any type of object, you can use Object as the parameter or return type:
1void printAnything(Object obj) {2 System.out.println(obj.getClass().getName() + ": " + obj.toString());3}Later, once you know the actual type, you can use instanceof and cast:
1if (obj1 instanceof Person) {2 Person p = (Person) obj1;3 // use p as a Person4}java.lang.Object. Every class implicitly extends Object if it doesn't extend any other class.6. Nested Classes Overview
Definition
A nested class is a class defined inside the body of another class.
1class OuterClass {2 class NestedClass { // ← nested class3 }4}When to Use Nested Classes
Use a nested class when a class is logically useful to only one other class and will never be needed independently. Instead of creating a separate .java file, you place it inside the class that uses it. This:
- Groups logically related code together
- Increases encapsulation
- Reduces namespace clutter
Full Taxonomy of Nested Classes
There are 5 distinct kinds of nested classes. Each has different rules for access, instantiation, and scope.
7. Static Nested Class
Definition
A static nested class is a nested class declared with thestatickeyword. It is associated with the outer class itself, not with any instance of the outer class.
Key Characteristics
| Property | Detail |
|---|---|
| Declared with | static keyword inside outer class |
| Access to outer instance variables? | ❌ No — only static members of outer class |
| Access to outer static variables? | ✅ Yes |
| Needs outer class object to instantiate? | ❌ No — access directly via outer class name |
| Access modifiers allowed | public, private, protected, or default |
Analogy
Think of it like a static method on a class. Just as a static method belongs to the class (not to any object), a static nested class belongs to the outer class, not to any instance of it.
Syntax
1class OuterClass {2 static int classVar = 10; // static variable3 int instanceVar = 20; // instance variable4
5 static class NestedClass { // ← static nested class6 void display() {7 System.out.println(classVar); // ✅ can access static member8 // System.out.println(instanceVar); // ❌ COMPILE ERROR — not static9 }10 }11}How to Instantiate a Static Nested Class
You do not need an object of the outer class. Access it directly through the outer class name:
1OuterClass.NestedClass obj = new OuterClass.NestedClass();2obj.display();Compare this to accessing a static method:
1OuterClass.staticMethod(); // access static method via class name2new OuterClass.NestedClass().display(); // access static nested class via class nameFull Code Example
1class OuterClass {2 static int classVariable = 100;3 int instanceVariable = 200;4
5 static class StaticNestedClass {6 void display() {7 System.out.println("Class variable: " + classVariable);8 // instanceVariable not accessible here9 }10 }11}12
13public class Main {14 public static void main(String[] args) {15 // No outer class object needed16 OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();17 nested.display();18 }19}Class variable: 100
Private Static Nested Class
A static nested class can be made private. In that case, it can only be accessed from within the outer class itself:
1class OuterClass {2 private static class PrivateNested {3 void secret() {4 System.out.println("Only OuterClass can see me.");5 }6 }7
8 void exposeSecret() {9 PrivateNested pn = new PrivateNested(); // ✅ created inside outer class10 pn.secret();11 }12}13
14public class Main {15 public static void main(String[] args) {16 // new OuterClass.PrivateNested(); // ❌ COMPILE ERROR — private17 OuterClass outer = new OuterClass();18 outer.exposeSecret(); // ✅ access via a public method19 }20}Only OuterClass can see me.
private, protected, public, or default access modifiers. This is unlike top-level classes, which can only be public or default.8. Non-Static Nested Class (Inner Class)
Definition
A non-static nested class (commonly called an inner class) is a nested class declared without thestatickeyword. It is associated with an instance of the outer class.
Key Characteristics
| Property | Detail |
|---|---|
| Declared with | No static keyword |
| Access to outer instance variables? | ✅ Yes — full access |
| Access to outer static variables? | ✅ Yes |
| Needs outer class object to instantiate? | ✅ Yes — must create outer object first |
| Access modifiers allowed | public, private, protected, or default |
Syntax
1class OuterClass {2 int instanceVar = 10;3 static int classVar = 20;4
5 class InnerClass { // ← non-static inner class6 void display() {7 System.out.println(instanceVar); // ✅ can access instance variable8 System.out.println(classVar); // ✅ can access static variable9 }10 }11}How to Instantiate a Non-Static Inner Class
You must first create an object of the outer class, then use that to create the inner class object:
1OuterClass outer = new OuterClass(); // Step 1: outer object2OuterClass.InnerClass inner = outer.new InnerClass(); // Step 2: inner object via outer3inner.display();Full Code Example
1class OuterClass {2 int instanceVar = 10;3 static int classVar = 20;4
5 class InnerClass {6 void print() {7 System.out.println("Instance var: " + instanceVar);8 System.out.println("Class var: " + classVar);9 }10 }11}12
13public class Main {14 public static void main(String[] args) {15 OuterClass outer = new OuterClass();16 OuterClass.InnerClass inner = outer.new InnerClass();17 inner.print();18 }19}Instance var: 10 Class var: 20
Static Nested vs Non-Static Inner Side-by-Side
| Feature | Static Nested Class | Non-Static Inner Class |
|---|---|---|
static keyword | ✅ Yes | ❌ No |
| Accesses outer instance variables | ❌ No | ✅ Yes |
| Accesses outer static variables | ✅ Yes | ✅ Yes |
| Instantiation | new Outer.Nested() | outer.new Inner() |
| Needs outer object | ❌ No | ✅ Yes |
| Association | Outer class | Outer class instance |
9. Member Inner Class
Definition
A member inner class is a non-static inner class defined directly inside the outer class body — at the "member level" (alongside fields and methods, not inside a method or block).
The inner class examples shown in Section 8 are member inner classes. The name distinguishes them from local inner classes (defined inside a method) and anonymous inner classes (defined without a name).
Key Points
- Has direct access to all instance and static members of the outer class.
- Can be given any access modifier:
public,private,protected, or default. - Instantiated using
outerObject.new InnerClass().
Code Example
1class OuterClass {2 private int data = 42;3
4 class MemberInner { // member inner class5 void display() {6 System.out.println("Outer data: " + data); // ✅ private data accessible!7 }8 }9}10
11public class Main {12 public static void main(String[] args) {13 OuterClass outer = new OuterClass();14 OuterClass.MemberInner inner = outer.new MemberInner();15 inner.display();16 }17}Outer data: 42
private members of the outer class. This is one of the key advantages of inner classes — tight encapsulation between tightly coupled classes.10. Local Inner Class
Definition
A local inner class is a class defined inside a block of code — such as inside a method, aforloop, anifblock, or awhileloop.
Key Characteristics
| Property | Detail |
|---|---|
| Defined inside | A method, loop, if-block, or any { } block |
| Scope | Only within the block where it is defined |
| Access modifiers allowed | ❌ None — cannot be public, private, or protected |
| Accesses outer members | ✅ Static and instance variables of outer class |
| Accesses block local variables | ✅ Only if they are effectively final |
| Can be instantiated outside the block? | ❌ No |
Why No Access Modifiers?
A local inner class lives entirely inside a method/block. Its lifetime is the same as the method call's stack frame — when the method returns, the memory is freed. There is no point giving it public or private since it cannot exist outside the block anyway.
Memory Note
When a method is called, the JVM allocates a stack frame for it. All local variables and local classes exist within this frame. When the method returns, the frame is popped off the stack and all its contents are gone. That is why a local inner class can only be instantiated and used inside the block where it is defined.
Code Example
1class OuterClass {2 int instanceVar = 10;3 static int classVar = 20;4
5 void display() {6 int methodVar = 30; // local variable — effectively final7
8 class LocalInner { // ← local inner class, defined inside a method9 void print() {10 System.out.println("Instance var: " + instanceVar); // ✅11 System.out.println("Class var: " + classVar); // ✅12 System.out.println("Method var: " + methodVar); // ✅13 }14 }15
16 LocalInner li = new LocalInner(); // ✅ instantiated inside the block17 li.print();18 // LocalInner is destroyed when display() returns19 }20}21
22public class Main {23 public static void main(String[] args) {24 OuterClass outer = new OuterClass();25 outer.display();26 // Cannot access LocalInner here — it doesn't exist outside display()27 }28}Instance var: 10 Class var: 20 Method var: 30
How to Use a Local Inner Class from Outside
You cannot — but you can call the method that uses it:
1OuterClass outer = new OuterClass();2outer.display(); // display() internally creates and uses LocalInner11. Anonymous Inner Class
Definition
An anonymous inner class is an inner class without a name. It is declared and instantiated in a single expression, typically to provide a one-time implementation of an abstract class or interface.
When to Use
When you want to override or implement a class/interface behavior once, without creating a full named subclass. It is ideal for short, single-use implementations.
How It Works Under the Hood
When you write an anonymous class, the Java compiler silently:
- Creates a hidden subclass with a compiler-generated name (e.g.,
OuterClass$1). - Makes it extend the abstract class (or implement the interface) you specified.
- Implements the method(s) with the body you wrote.
- Creates an instance of that hidden subclass.
- Assigns the reference to the variable you declared.
You write one expression; the compiler generates an entire class file behind the scenes.
Syntax
1AbstractClass ref = new AbstractClass() {2 @Override3 void abstractMethod() {4 // your implementation here5 }6}; // ← semicolon — this is a statementCode Example Without Anonymous Class (Verbose Way)
1abstract class Car {2 abstract void pressBrake();3}4
5class Audi extends Car { // must create a new file / class6 @Override7 void pressBrake() {8 System.out.println("Audi brake applied.");9 }10}11
12public class Main {13 public static void main(String[] args) {14 Audi a = new Audi();15 a.pressBrake();16 }17}Code Example With Anonymous Class (Concise Way)
1abstract class Car {2 abstract void pressBrake();3}4
5public class Main {6 public static void main(String[] args) {7 Car audiCar = new Car() { // ← anonymous class8 @Override9 void pressBrake() {10 System.out.println("Anonymous Audi brake applied.");11 }12 }; // ← semicolon required13
14 audiCar.pressBrake();15 }16}Anonymous Audi brake applied.
Line-by-Line Explanation
| Line | Meaning |
|---|---|
Car audiCar = | Declare a reference variable of type Car |
new Car() { | Start creating an anonymous subclass of Car |
void pressBrake() { ... } | Implement the abstract method |
}; | End of the anonymous class expression and statement |
audiCar.pressBrake(); | Call the implemented method via the Car reference |
What the Compiler Generates (Conceptually)
1// This is what the compiler creates INVISIBLY:2class Main$1 extends Car {3 @Override4 void pressBrake() {5 System.out.println("Anonymous Audi brake applied.");6 }7}8
9// Then assigns: Car audiCar = new Main$1();You can verify this by looking at the compiled .class files — you will see a file named Main$1.class alongside Main.class.
Anonymous Class with an Interface
Anonymous classes work equally well with interfaces:
1interface Greeting {2 void sayHello();3}4
5public class Main {6 public static void main(String[] args) {7 Greeting g = new Greeting() { // anonymous class implementing interface8 @Override9 public void sayHello() {10 System.out.println("Hello from anonymous class!");11 }12 };13 g.sayHello();14 }15}Hello from anonymous class!
java
// Lambda version (Java 8+ only, for single-method interfaces)
Greeting g = () -> System.out.println("Hello from lambda!");
``12. Inheritance in Nested Classes
Nested classes support inheritance just like regular classes. There are three main scenarios:
Scenario 1 Inner Class Inheriting Another Inner Class (Same Outer Class)
1class OuterClass {2 class InnerClass1 {3 int data = 10;4 void display() {5 System.out.println("InnerClass1 display, data = " + data);6 }7 }8
9 class InnerClass2 extends InnerClass1 { // inherits from sibling inner class10 int extra = 99;11 void show() {12 System.out.println("InnerClass2 show, extra = " + extra);13 display(); // inherited from InnerClass114 }15 }16}17
18public class Main {19 public static void main(String[] args) {20 OuterClass outer = new OuterClass();21 OuterClass.InnerClass2 ic2 = outer.new InnerClass2();22 ic2.show();23 ic2.display(); // inherited method accessible24 }25}InnerClass2 show, extra = 99 InnerClass1 display, data = 10 InnerClass1 display, data = 10
Scenario 2 External Class Inheriting a Static Nested Class
Since a static nested class is associated with the outer class (not an instance), extending it from an outside class is straightforward:
1class OuterClass {2 static class StaticNestedClass {3 void display() {4 System.out.println("StaticNestedClass display.");5 }6 }7}8
9class SomeOtherClass extends OuterClass.StaticNestedClass {10 void show() {11 System.out.println("SomeOtherClass show.");12 display(); // inherited from StaticNestedClass13 }14}15
16public class Main {17 public static void main(String[] args) {18 SomeOtherClass obj = new SomeOtherClass();19 obj.show();20 }21}SomeOtherClass show. StaticNestedClass display.
Scenario 3 External Class Inheriting a Non-Static Inner Class
This is the trickiest case. Since a non-static inner class is associated with an instance of the outer class, you must explicitly create an outer class instance and call super() using it.
1class OuterClass {2 class InnerClass {3 void display() {4 System.out.println("InnerClass display.");5 }6 }7}8
9class SomeOtherClass extends OuterClass.InnerClass {10 SomeOtherClass() {11 // Must create an OuterClass instance first, then call super via it12 new OuterClass().super(); // ← required to initialize the InnerClass part13 }14
15 void show() {16 System.out.println("SomeOtherClass show.");17 display(); // inherited from InnerClass18 }19}20
21public class Main {22 public static void main(String[] args) {23 SomeOtherClass obj = new SomeOtherClass();24 obj.show();25 }26}SomeOtherClass show. InnerClass display.
Why `new OuterClass().super()`?
When SomeOtherClass extends InnerClass, calling the parent constructor (super()) requires an instance of OuterClass because InnerClass is tied to an OuterClass instance. The new OuterClass().super() syntax creates a temporary OuterClass instance and uses it to call InnerClass's constructor.
13. Access Modifiers Full Comparison
Top-Level Classes
| Modifier | Top-Level Class | Meaning |
|---|---|---|
public | ✅ Allowed | Accessible from any package |
| (default) | ✅ Allowed | Accessible only within the same package |
private | ❌ Not allowed | N/A |
protected | ❌ Not allowed | N/A |
Nested Classes (All Types)
| Modifier | Static Nested | Member Inner | Local Inner | Anonymous |
|---|---|---|---|---|
public | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ❌ | ❌ |
| (default) | ✅ | ✅ | ✅ | ❌ |
private | ✅ | ✅ | ❌ | ❌ |
Local and anonymous inner classes cannot be given access modifiers because their scope is inherently confined to a single block.
14. Mermaid Diagrams
Complete Nested Class Taxonomy
Abstract Class Hierarchy
Object Class Hierarchy
Instantiation Rules Decision Flowchart
15. Quick-Reference Tables
All Nested Class Types at a Glance
| Type | Static? | Access to Instance Vars | Access Modifiers | Instantiation |
|---|---|---|---|---|
| Static Nested Class | ✅ Yes | ❌ No | public/protected/default/private | new Outer.Nested() |
| Member Inner Class | ❌ No | ✅ Yes | public/protected/default/private | outer.new Inner() |
| Local Inner Class | ❌ No | ✅ Yes | None (no modifier) | Inside block only |
| Anonymous Inner Class | ❌ No | ✅ Yes | None (no modifier) | new Type() { ... } |
Abstract Class vs Concrete Class vs Interface
| Feature | Concrete Class | Abstract Class | Interface |
|---|---|---|---|
| Can instantiate? | ✅ | ❌ | ❌ |
| Can have abstract methods? | ❌ | ✅ | ✅ (all methods, pre-Java 8) |
| Can have concrete methods? | ✅ | ✅ | ✅ (only default/static, Java 8+) |
| Can have constructors? | ✅ | ✅ | ❌ |
| Can have instance variables? | ✅ | ✅ | ❌ (only constants) |
| Multiple inheritance | ❌ | ❌ | ✅ |
16. Common Mistakes
Mistake 1: Trying to Instantiate an Abstract Class
1abstract class Car {2 abstract void brake();3}4
5Car c = new Car(); // ❌ COMPILE ERROR: Car is abstract; cannot be instantiatedFix: Create a concrete subclass:
1class Audi extends Car {2 @Override3 void brake() { System.out.println("Audi brakes."); }4}5Car c = new Audi(); // ✅Mistake 2: Accessing Instance Variable from Static Nested Class
1class Outer {2 int instanceVar = 5;3
4 static class Nested {5 void show() {6 System.out.println(instanceVar); // ❌ COMPILE ERROR7 }8 }9}Fix: Access only static members, or pass the outer instance as a parameter.
Mistake 3: Forgetting Outer Object When Creating Non-Static Inner Class
1OuterClass.InnerClass obj = new OuterClass.InnerClass(); // ❌ COMPILE ERRORFix:
1OuterClass outer = new OuterClass();2OuterClass.InnerClass obj = outer.new InnerClass(); // ✅Mistake 4: Missing Semicolon After Anonymous Class
1Car c = new Car() {2 void brake() { System.out.println("braking"); }3} // ❌ COMPILE ERROR — missing semicolonFix:
1Car c = new Car() {2 void brake() { System.out.println("braking"); }3}; // ✅ semicolon required — this is a statementMistake 5: Giving Access Modifiers to a Local Inner Class
1void myMethod() {2 private class LocalInner { } // ❌ COMPILE ERROR — modifiers not allowed3}Fix: Remove the modifier:
1void myMethod() {2 class LocalInner { } // ✅3}Mistake 6: Thinking a Class Without `extends` Has No Parent
1class Person { } // appears to have no parentThis is incorrect. Java implicitly adds extends Object, so Person always has Object as its parent.
17. Best Practices
- Use abstract classes when related classes share common state (fields) or behavior, and you want to enforce a template pattern.
- Prefer interfaces over abstract classes when you only need to define a contract (no shared state needed), especially since a class can implement multiple interfaces.
- Use nested classes sparingly — only when the nested class is truly meaningful only in the context of the outer class. Over-using nesting makes code hard to read.
- Prefer static nested classes over inner classes when the nested class does not need access to instance variables of the outer class. This is more memory-efficient (no hidden reference to the outer instance).
- Use anonymous classes for short, one-time-use implementations of interfaces or abstract classes. For anything longer or reused, create a named class.
- Override
toString(),equals(), andhashCode()fromObjectwhenever you create classes whose instances will be printed, compared, or stored in collections.
- Never declare a top-level class as
privateorprotected— it will not compile. Reserve those modifiers for nested classes.
- Document why a nested class is nested — the "only used by one class" justification should be clear to future readers.
18. Interview Notes
Most Frequently Asked Questions
Q1: What is the difference between an abstract class and an interface?
A: An abstract class can have both abstract and concrete methods, constructors, and instance variables. It supports 0–100% abstraction. An interface (pre-Java 8) only has abstract methods (100% abstraction). A class can implement multiple interfaces but extend only one class.
Q2: Can you instantiate an abstract class?
A: No. You can only instantiate a concrete subclass of it. However, you can hold a reference of the abstract class type pointing to a concrete subclass object.
Q3: What is the parent class of all classes in Java?
A: java.lang.Object. Every class that doesn't explicitly extend another class implicitly extends Object.
Q4: What methods does the Object class provide?
A: toString(), equals(), hashCode(), getClass(), clone(), wait(), notify(), notifyAll(), finalize().
Q5: What is a nested class? When would you use one?
A: A class defined inside another class. Use it when a class is only useful in the context of one other class — grouping them logically in a single file increases encapsulation and readability.
Q6: What is the difference between a static nested class and a non-static inner class?
A: A static nested class is associated with the outer class and can only access the outer class's static members. It is instantiated without an outer class object: new Outer.Nested(). A non-static inner class is associated with an outer class instance, can access all outer members including instance variables, and requires an outer object to instantiate: outer.new Inner().
Q7: Can a nested class be private?
A: Yes. Unlike top-level classes, nested classes can use any access modifier: public, protected, default, or private. A private nested class can only be accessed from within the outer class.
Q8: What is an anonymous class?
A: A class without a name, declared and instantiated in a single expression. Typically used to provide a one-time implementation of an abstract class or interface. The compiler generates a hidden subclass with a compiler-assigned name.
Q9: What is a local inner class?
A: A class defined inside a method or block. Its scope is limited to that block. It cannot have access modifiers. It is created and used only within the block where it is defined.
Q10: What happens when you compile code containing an anonymous class?
A: The compiler generates a separate .class file for the anonymous class, named something like Outer$1.class. It creates a subclass of the specified type, implements the method(s) you wrote, creates an instance, and assigns the reference to your variable.
Q11: Can abstract classes have constructors?
A: Yes. Abstract class constructors cannot be called directly (since you can't instantiate the abstract class), but they are called via super() when a concrete subclass is instantiated.
Q12: What is the access modifier of a top-level class?
A: Only public or package-private (default — no keyword). private and protected are not allowed for top-level classes.
19. Practice Questions
Easy
- What keyword is used to declare an abstract class?
- Can you create an object of an abstract class? Why or why not?
- What is the parent class of every Java class?
- What is a concrete class?
- What is the difference between a superclass and a subclass?
Medium
- Create an abstract class
Animalwith an abstract methodmakeSound()and a concrete methodbreathe(). Create two concrete subclassesDogandCatthat implementmakeSound(). Demonstrate polymorphism.
- Write code that stores a
Dogobject in anAnimalreference and callsmakeSound().
- Explain the difference between a static nested class and a member inner class. Write a code example showing both and how to instantiate each.
- Create a class with a private static nested class. Show how to access it from within the outer class via a public method.
- Rewrite the following using an anonymous class — without creating any named subclass:
1 abstract class Greeter {2 abstract void greet();3 }Hard
- Create an outer class
Librarywith a non-static inner classBook. TheBookclass should have access to theLibrary'slibraryNamefield. Instantiate aBookfrom a separate class.
- Create a local inner class inside a method. Show that it can access the method's local variable. Explain what "effectively final" means in this context.
- Demonstrate Scenario 3 from Section 12 (external class inheriting a non-static inner class). Explain why
new OuterClass().super()is required.
- What is the output of the following? Explain each line:
1 class Outer {2 static int x = 10;3 int y = 20;4 static class Nested {5 void show() { System.out.println(x); }6 }7 class Inner {8 void show() { System.out.println(y); }9 }10 }11 public class Test {12 public static void main(String[] args) {13 new Outer.Nested().show();14 new Outer().new Inner().show();15 }16 }- Write a program using an anonymous class to implement an interface
Comparator(or any single-method interface of your choice) and sort an array of integers in descending order.
20. Summary Cheat Sheet
1┌─────────────────────────────────────────────────────────────────────────────┐2│ JAVA TYPES OF CLASSES — QUICK SUMMARY (Part 1) │3├─────────────────────────────────────────────────────────────────────────────┤4│ CONCRETE CLASS │5│ Any class instantiable with 'new'. All methods have bodies. │6│ Top-level access: public OR default only. │7├─────────────────────────────────────────────────────────────────────────────┤8│ ABSTRACT CLASS │9│ Declared with 'abstract'. Cannot instantiate directly. │10│ Can have abstract methods (no body) + concrete methods (with body). │11│ Child must implement all abstract methods OR also be abstract. │12│ Achieves 0–100% abstraction. │13├─────────────────────────────────────────────────────────────────────────────┤14│ SUPER CLASS / SUB CLASS │15│ Superclass = parent. Subclass = child (extends parent). │16│ 'class B extends A' → B is subclass, A is superclass. │17├─────────────────────────────────────────────────────────────────────────────┤18│ OBJECT CLASS │19│ Parent of ALL Java classes (implicit if no extends). │20│ Provides: toString, equals, hashCode, getClass, clone, wait, notify │21├─────────────────────────────────────────────────────────────────────────────┤22│ NESTED CLASSES │23│ Static Nested → 'static' inside outer; only static members of outer; │24│ new Outer.Nested() │25│ Member Inner → no 'static'; all outer members; outer.new Inner() │26│ Local Inner → inside method/block; no access modifier; block scope │27│ Anonymous Inner → no name; new Type() { impl }; compiler names it │28├─────────────────────────────────────────────────────────────────────────────┤29│ ACCESS MODIFIERS │30│ Top-level class: public or default ONLY │31│ Nested class: public / protected / default / private ALL allowed │32│ Local inner: NO access modifier │33└─────────────────────────────────────────────────────────────────────────────┘End of Chapter — Types of Classes in Java (Part 1)
Next: Part 2 — Generic Classes · POJOs · Enums · Final Class · Singleton · Immutable Class · Wrapper Class
Mastery check
How well can you recall this?
Finished this lesson?