Advanced Java
Inner Classes & Lambdas
Complete lesson for Inner Classes & Lambdas using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Inner Classes & Lambdas
Section: Advanced Java. Classes inside classes (member inner, static nested, local, anonymous) and lambdas with functional interfaces and method references — explained with real-life examples.
What are inner (nested) classes?
- A nested class is a class declared inside another class. Java has four kinds: member inner class, static nested class, local class, and anonymous class.
- Use them to group classes that are only useful together, to hide helper classes, and to let a helper read the private members of its outer class.
- Real life: a
Carhas anEngine. An engine made for that car has no meaning on its own, soEnginelives insideCar. - The compiler creates a separate
.classfile for each nested class, such asCar$Engine.class.
public class Car {
private final String model;
private int speed = 0;
Car(String model) {
this.model = model;
}
class Engine { // inner class: belongs to one Car object
void accelerate(int by) {
speed += by; // can use the private field of Car
System.out.println(model + " speed: " + speed + " km/h");
}
}
public static void main(String[] args) {
Car car = new Car("Nexon");
Car.Engine engine = car.new Engine();
engine.accelerate(40); // Nexon speed: 40 km/h
engine.accelerate(20); // Nexon speed: 60 km/h
}
} Types of nested classes in Java
| Type | Declared | Needs outer object? | Can use outer instance members? | How to create | Real life |
|---|---|---|---|---|---|
| Member inner class | Inside the class, outside methods | Yes | Yes, even private | outer.new Inner() | Engine of a specific car |
| Static nested class | Inside the class with static | No | Only through an object reference | new Outer.Nested() | Builder that creates a pizza |
| Local class | Inside a method or block | Only in instance methods | Yes, plus effectively final locals | new Local() inside that method | A helper hired for one task only |
| Anonymous class | Inside an expression, no name | Same as local | Yes, plus effectively final locals | new Interface() { ... } | A one-time guest speaker |
Member inner class
- A non-static class declared at member level. Every inner object is tied to one outer object and keeps a hidden reference to it.
- It can read and change all members of the outer class, including private ones.
- Create it from outside with
outerObject.new Inner(). Inside the outer class, plainnew Inner()works in instance methods. - If names clash, use
Outer.this.fieldto reach the outer field. - Real life: a mobile phone and its battery. The battery status always refers to that phone.
public class MobilePhone {
private final String model;
private int charge = 40;
MobilePhone(String model) {
this.model = model;
}
class Battery { // member inner class
private int charge = 5000; // capacity in mAh (same name as outer field)
void plugIn(int percent) {
MobilePhone.this.charge = Math.min(100, MobilePhone.this.charge + percent);
}
void status() {
System.out.println(model + " battery " + this.charge + " mAh, charged "
+ MobilePhone.this.charge + "%");
}
}
public static void main(String[] args) {
MobilePhone phone = new MobilePhone("Galaxy M14");
MobilePhone.Battery battery = phone.new Battery(); // needs an outer object
battery.plugIn(35);
battery.status(); // Galaxy M14 battery 5000 mAh, charged 75%
}
} Static nested class
- Declared with
staticinside another class. It does not hold a reference to an outer object, so you create it withnew Outer.Nested(). - It can use static members of the outer class directly, and private instance members only through an object.
- Best choice when the helper does not need an outer instance: builders, nodes of a linked list,
Map.Entry-style pairs, and constants. - Real life: a pizza shop order form (Builder). You fill it in before any pizza exists, then the shop builds the pizza from it.
public class Pizza {
private final String size;
private final boolean cheese;
private final boolean paneer;
private Pizza(Builder b) {
this.size = b.size;
this.cheese = b.cheese;
this.paneer = b.paneer;
}
static class Builder { // static nested: no Pizza object needed
private final String size;
private boolean cheese;
private boolean paneer;
Builder(String size) { this.size = size; }
Builder addCheese() { cheese = true; return this; }
Builder addPaneer() { paneer = true; return this; }
Pizza build() { return new Pizza(this); }
}
@Override
public String toString() {
return size + " pizza" + (cheese ? " + cheese" : "") + (paneer ? " + paneer" : "");
}
public static void main(String[] args) {
Pizza order = new Pizza.Builder("Medium").addCheese().addPaneer().build();
System.out.println(order); // Medium pizza + cheese + paneer
}
} Differences between inner class and static nested class
| Point | Member inner class | Static nested class |
|---|---|---|
| Keyword | No static | static |
| Outer object needed? | Yes | No |
| Hidden reference to outer | Yes (Outer.this) | No |
| Access to outer instance fields | Direct | Only through an object reference |
| Access to outer static fields | Direct | Direct |
| Creation from outside | outer.new Inner() | new Outer.Nested() |
| Memory | Keeps the outer object alive | Lighter, no extra reference |
| Typical use | Iterator over the outer data | Builder, Node, Entry, helpers |
| Real life | Engine of one specific car | A car brochure: useful without a car |
Local inner class
- A class declared inside a method or block. It is visible only inside that method.
- It can use the method parameters and local variables, but only if they are final or effectively final (never reassigned).
- Real life: a temporary helper hired for one event. Outside that event, nobody knows about them.
public class BillPrinter {
static void printBill(String customer, double gstRate) {
class LineItem { // local class: only inside printBill
final String name;
final double price;
LineItem(String name, double price) {
this.name = name;
this.price = price;
}
double total() {
return price + price * gstRate; // uses an effectively final parameter
}
}
LineItem[] items = { new LineItem("Notebook", 100), new LineItem("Pen", 20) };
double sum = 0;
System.out.println("Bill for " + customer);
for (LineItem item : items) {
System.out.printf("%-10s %8.2f%n", item.name, item.total());
sum += item.total();
}
System.out.printf("%-10s %8.2f%n", "TOTAL", sum);
}
public static void main(String[] args) {
printBill("Asha", 0.18);
// Notebook 118.00, Pen 23.60, TOTAL 141.60
}
} Anonymous inner class
- A class without a name, declared and instantiated in one expression:
new Interface() { ... }ornew AbstractClass() { ... }. - Use it for a one-time implementation. It can override several methods and keep its own fields.
- Before Java 8, anonymous classes were the usual way to write event listeners, comparators, and threads.
- Real life: a guest speaker invited for one session. They do the job once and are not on the staff list.
interface OnClickListener {
void onClick(String button);
}
abstract class Greeting {
abstract void greet(String name);
}
public class AnonymousDemo {
public static void main(String[] args) {
OnClickListener payButton = new OnClickListener() { // implements an interface
private int clicks = 0; // anonymous classes can keep state
@Override
public void onClick(String button) {
clicks++;
System.out.println(button + " clicked " + clicks + " time(s)");
}
};
payButton.onClick("Pay Now"); // Pay Now clicked 1 time(s)
payButton.onClick("Pay Now"); // Pay Now clicked 2 time(s)
Greeting festival = new Greeting() { // extends an abstract class
@Override
void greet(String name) {
System.out.println("Happy Diwali, " + name + "!");
}
};
festival.greet("Ravi");
}
} What is a lambda expression?
- A lambda is a short, unnamed function you can pass around like a value. It was added in Java 8.
- It provides the body of the single abstract method of a functional interface, so it replaces most one-method anonymous classes.
- Real life: instead of hiring a whole agency (anonymous class) for one small job, you hand a friend a sticky note saying exactly what to do.
- Lambdas make code shorter and enable the Stream API,
forEach,removeIf, andComparatorchains.
public class LambdaIntro {
public static void main(String[] args) {
Runnable oldWay = new Runnable() { // anonymous class: 6 lines
@Override
public void run() {
System.out.println("Sending OTP (anonymous class)");
}
};
Runnable newWay = () -> System.out.println("Sending OTP (lambda)"); // 1 line
oldWay.run();
newWay.run();
}
} Lambda syntax forms
| Form | Example | Meaning |
|---|---|---|
| No parameters | () -> System.out.println("Hi") | Runnable-style action |
| One parameter | n -> n * 2 | Parentheses optional for one untyped parameter |
| Two parameters | (a, b) -> a + b | Parentheses required |
| Typed parameters | (int a, int b) -> a + b | Types written explicitly |
| var parameters (Java 11) | (var a, var b) -> a + b | Allows annotations on parameters |
| Block body | (a, b) -> { int s = a + b; return s; } | Braces need return for a value |
| Expression body | s -> s.isEmpty() | Value returned automatically |
Functional interfaces
- A functional interface has exactly one abstract method (SAM: Single Abstract Method). A lambda can be assigned only to such an interface.
- It may also have any number of
defaultandstaticmethods, and methods fromObjectsuch asequalsdo not count. - Add
@FunctionalInterfaceso the compiler reports an error if someone adds a second abstract method. - Real life: a power socket has one job (supply power). Any plug that fits (lambda) can be used.
@FunctionalInterface
interface Discount {
double apply(double amount); // exactly one abstract method
default Discount then(Discount next) { // default methods are allowed
return amount -> next.apply(apply(amount));
}
}
public class DiscountDemo {
public static void main(String[] args) {
Discount festival = amount -> amount - amount * 10 / 100; // 10% off
Discount student = amount -> amount - 50; // flat Rs.50 off
Discount none = amount -> amount;
double price = 1000;
System.out.println("Festival: " + festival.apply(price)); // 900.0
System.out.println("Student: " + student.apply(price)); // 950.0
System.out.println("Festival then student: " + festival.then(student).apply(price)); // 850.0
System.out.println("None: " + none.apply(price)); // 1000.0
}
} Built-in functional interfaces (java.util.function)
- Java already provides common functional interfaces, so you rarely need to write your own.
| Interface | Method | Takes / returns | Example | Real life |
|---|---|---|---|---|
Predicate<T> | test(T) | T to boolean | age -> age >= 18 | Is this person eligible to vote? |
Function<T, R> | apply(T) | T to R | s -> s.length() | Convert rupees to dollars |
Consumer<T> | accept(T) | T to nothing | msg -> send(msg) | Send an SMS |
Supplier<T> | get() | nothing to T | () -> generateOtp() | OTP generator |
UnaryOperator<T> | apply(T) | T to T | s -> s.toUpperCase() | Apply a filter to a photo |
BinaryOperator<T> | apply(T, T) | T, T to T | (a, b) -> a + b | Add two bills |
BiFunction<T, U, R> | apply(T, U) | T, U to R | (price, qty) -> price * qty | Price times quantity |
BiConsumer<T, U> | accept(T, U) | T, U to nothing | (k, v) -> print(k, v) | Print a name and phone number |
Runnable | run() | nothing to nothing | () -> backup() | Start a backup job |
Comparator<T> | compare(T, T) | T, T to int | (a, b) -> a.price - b.price | Sort products by price |
import java.util.Random;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class BuiltInDemo {
public static void main(String[] args) {
Predicate<Integer> canVote = age -> age >= 18;
Function<String, Integer> wordCount = text -> text.split(" ").length;
Consumer<String> sendSms = msg -> System.out.println("SMS: " + msg);
Supplier<Integer> otp = () -> 100000 + new Random().nextInt(900000);
UnaryOperator<String> shout = s -> s.toUpperCase();
BinaryOperator<Integer> add = (a, b) -> a + b;
BiFunction<Double, Integer, Double> bill = (price, qty) -> price * qty;
System.out.println(canVote.test(20)); // true
System.out.println(wordCount.apply("learn java with fun")); // 4
sendSms.accept("Your order is shipped"); // SMS: Your order is shipped
System.out.println("OTP: " + otp.get()); // random 6-digit number
System.out.println(shout.apply("sale")); // SALE
System.out.println(add.apply(40, 2)); // 42
System.out.println(bill.apply(250.0, 3)); // 750.0
}
} Effectively final and variable capture
- Lambdas, local classes, and anonymous classes can use local variables of the enclosing method only if those variables are final or effectively final.
- Effectively final means the variable is assigned once and never changed, even without the
finalkeyword. - Reason: the lambda may run later or on another thread, so Java captures a copy of the value. Changing the original would make the copy wrong.
- Instance and static fields are not restricted, because the lambda reads them through
thisor the class.
import java.util.List;
public class CaptureDemo {
public static void main(String[] args) {
int passMarks = 35; // effectively final: never reassigned
List<Integer> marks = List.of(20, 45, 90, 33, 60);
marks.forEach(m -> {
if (m >= passMarks) { // OK: captures passMarks
System.out.println("Pass: " + m);
}
});
// passMarks = 40; // uncommenting makes the lambda above a compile error
int[] passCount = { 0 }; // workaround: change an array element (not thread-safe)
marks.forEach(m -> { if (m >= passMarks) passCount[0]++; });
System.out.println("Passed: " + passCount[0]); // 3
}
} Method references
- A method reference is a shorter lambda that only calls an existing method:
ClassName::methodorobject::method. - Real life: instead of explaining the whole recipe, you say "follow page 42 of the cookbook".
| Kind | Syntax | Example | Equivalent lambda |
|---|---|---|---|
| Static method | Class::staticMethod | Integer::parseInt | s -> Integer.parseInt(s) |
| Instance method of a particular object | object::method | System.out::println | x -> System.out.println(x) |
| Instance method of an arbitrary object | Class::instanceMethod | String::toUpperCase | s -> s.toUpperCase() |
| Constructor | Class::new | ArrayList::new | () -> new ArrayList<>() |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodRefDemo {
public static void main(String[] args) {
Function<String, Integer> parse = Integer::parseInt; // static method
List<Integer> prices = new ArrayList<>();
for (String p : Arrays.asList("499", "99", "1299")) {
prices.add(parse.apply(p));
}
List<String> cities = Arrays.asList("Pune", "delhi", "Chennai");
cities.replaceAll(String::toUpperCase); // arbitrary object
cities.forEach(System.out::println); // particular object
Supplier<List<String>> newCart = ArrayList::new; // constructor
List<String> cart = newCart.get();
cart.add("Headphones");
System.out.println(prices + " " + cart); // [499, 99, 1299] [Headphones]
}
} Differences between anonymous class and lambda
| Point | Anonymous class | Lambda |
|---|---|---|
| Target type | Any interface or class (abstract or concrete) | Only a functional interface |
| Number of methods | Can override many methods | Implements exactly one method |
| State (fields) | Can declare its own fields | Cannot declare fields |
Meaning of this | The anonymous object itself | The enclosing class object |
| New scope | Yes: can redeclare local variable names | No: shares the enclosing method scope |
| Class file | Creates Outer$1.class | No extra class file; created at runtime with invokedynamic |
| Code length | Long | Short |
| Use when | Several methods, state, or extending a class | Simple one-method behaviour |
Advanced — Inner Classes & Lambdas
this and Outer.this in inner classes, anonymous classes, and lambdas
- In an inner class,
thisis the inner object andOuter.thisis the enclosing object. - In an anonymous class,
thisis the anonymous object, so outer fields with the same name needOuter.this. - In a lambda,
thismeans the enclosing object. A lambda does not introduce a newthis.
public class ThisDemo {
private final String name = "Outer";
class Inner {
private final String name = "Inner";
void show() {
System.out.println("inner this.name: " + this.name); // Inner
System.out.println("Outer.this.name: " + ThisDemo.this.name); // Outer
}
}
void compare() {
Runnable anon = new Runnable() {
@Override
public void run() {
System.out.println("anonymous this is the Runnable: " + (this instanceof Runnable)); // true
// this.name does not compile here: this = the anonymous object
}
};
Runnable lambda = () -> System.out.println("lambda this.name: " + this.name); // Outer
anon.run();
lambda.run();
}
public static void main(String[] args) {
ThisDemo demo = new ThisDemo();
demo.new Inner().show();
demo.compare();
}
} Scope and shadowing rules
| Situation | Inner / anonymous class | Lambda |
|---|---|---|
| Declare a local with the same name as an enclosing local | Allowed (shadows it) | Compile error: already defined |
| Parameter with the same name as an enclosing local | Allowed | Compile error |
| Change an enclosing local | Not allowed | Not allowed |
| Change an enclosing field | Allowed | Allowed |
| Reach a hidden outer field | Outer.this.field | this.field (same as the outer) |
public class ScopeDemo {
private int bonus = 1000;
void run() {
int salary = 50000;
Runnable anon = new Runnable() {
@Override
public void run() {
int salary = 70000; // OK: new scope, shadows the outer local
System.out.println("anonymous salary: " + salary); // 70000
}
};
// Runnable bad = () -> { int salary = 70000; }; // ERROR: salary is already defined
Runnable lambda = () -> {
bonus += 500; // OK: fields can change
System.out.println("lambda total: " + (salary + bonus)); // 51500
};
anon.run();
lambda.run();
}
public static void main(String[] args) {
new ScopeDemo().run();
}
} Hidden outer reference and memory leaks
- Every member inner object, and every anonymous or local class object created in an instance method, holds a hidden reference to the outer object.
- If the inner object lives long (stored in a cache, a static list, or a listener registry), the whole outer object cannot be garbage collected.
- Lambdas capture
thisonly when they use an instance member; otherwise they keep no outer reference. - Rule: make nested classes
staticunless they truly need the outer instance. - Real life: you borrow a library card for one book, but the card keeps the entire library account locked until you return it.
import java.util.ArrayList;
import java.util.List;
public class Report {
private final byte[] bigData = new byte[10_000_000]; // 10 MB inside every Report
class Row { } // inner: each Row secretly keeps Report.this alive
static class SafeRow { } // static nested: no hidden reference
public static void main(String[] args) {
List<Object> cache = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Report r = new Report();
cache.add(r.new Row()); // keeps 5 x 10 MB alive through Row -> Report
cache.add(new SafeRow()); // keeps only a tiny object alive
}
System.out.println("Cached rows: " + cache.size());
}
} Lambdas with collections
- Collections have lambda-friendly methods:
forEach,removeIf,replaceAll,sort, and maps haveforEach,merge,computeIfAbsent,getOrDefault. Comparator.comparing(...),thenComparing(...), andreversed()build readable sort rules.- Real life: a shopping cart that removes cheap freebies, sorts by category, and totals each category.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CartDemo {
record Item(String name, String category, int price) { }
public static void main(String[] args) {
List<Item> cart = new ArrayList<>(List.of(
new Item("Shoes", "Fashion", 2499),
new Item("Charger", "Electronics", 799),
new Item("Socks", "Fashion", 199),
new Item("Earbuds", "Electronics", 1999)
));
cart.removeIf(i -> i.price() < 200); // drop cheap items
cart.sort(Comparator.comparing(Item::category)
.thenComparing(Item::price, Comparator.reverseOrder()));
cart.forEach(i -> System.out.println(i.category() + " | " + i.name() + " | " + i.price()));
Map<String, Integer> totals = new HashMap<>();
cart.forEach(i -> totals.merge(i.category(), i.price(), Integer::sum));
totals.forEach((cat, sum) -> System.out.println(cat + " total = " + sum));
// Electronics total = 2798, Fashion total = 2499
}
} Composing functions: and, or, negate, andThen
Predicatehasand,or,negate, andPredicate.not(...)(Java 11) to combine conditions.FunctionhasandThen(run this, then the next) andcompose(run the other first).Consumeralso hasandThen.ComparatorhasthenComparing,reversed,nullsFirst, andnullsLast.- Real life: an HR shortlist rule built from small checks: experienced AND knows Java AND NOT too expensive.
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
public class HiringFilter {
record Candidate(String name, int experience, boolean knowsJava, int expectedSalary) { }
public static void main(String[] args) {
Predicate<Candidate> experienced = c -> c.experience() >= 2;
Predicate<Candidate> javaDev = Candidate::knowsJava;
Predicate<Candidate> tooCostly = c -> c.expectedSalary() > 1_200_000;
Predicate<Candidate> shortlist = experienced.and(javaDev).and(tooCostly.negate());
Function<String, String> clean = String::trim;
Function<String, String> letterName = clean.andThen(String::toUpperCase).andThen(n -> "Dear " + n);
List<Candidate> applicants = List.of(
new Candidate("Asha", 3, true, 900_000),
new Candidate("Ravi", 1, true, 600_000),
new Candidate("Kiran", 5, true, 1_500_000),
new Candidate("Meena", 4, false, 800_000)
);
for (Candidate c : applicants) {
if (shortlist.test(c)) {
System.out.println(letterName.apply(" " + c.name() + " ") + ", you are shortlisted");
}
}
// Dear ASHA, you are shortlisted
}
} Lambdas and checked exceptions
- Built-in functional interfaces such as
FunctionandConsumerdo not declare checked exceptions, so a lambda calling a method that throwsIOExceptionwill not compile. - Options: handle the exception inside the lambda, write your own functional interface whose method declares
throws, or wrap the checked exception in an unchecked one.
import java.util.List;
import java.util.function.Function;
public class CheckedInLambda {
static String readFile(String name) throws Exception {
if (name.endsWith(".txt")) return "contents of " + name;
throw new Exception("Unsupported file: " + name);
}
@FunctionalInterface
interface ThrowingFunction<T, R> {
R apply(T t) throws Exception; // our own interface may throw
}
static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
return t -> {
try {
return f.apply(t);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
};
}
public static void main(String[] args) {
// List.of("a.txt").forEach(f -> readFile(f)); // ERROR: unhandled exception
Function<String, String> safeRead = unchecked(CheckedInLambda::readFile);
for (String f : List.of("notes.txt", "photo.jpg")) {
try {
System.out.println(safeRead.apply(f));
} catch (RuntimeException e) {
System.out.println("Skipped: " + e.getMessage());
}
}
}
} Primitive functional interfaces
Function<Integer, Integer>boxes every number into anIntegerobject. Primitive versions avoid boxing and are faster in loops and streams.
| Interface | Method | Example |
|---|---|---|
IntPredicate | boolean test(int) | n -> n % 2 == 0 |
IntFunction<R> | R apply(int) | n -> "Table " + n |
ToIntFunction<T> | int applyAsInt(T) | String::length |
IntUnaryOperator | int applyAsInt(int) | n -> n * n |
IntBinaryOperator | int applyAsInt(int, int) | Math::max |
IntSupplier | int getAsInt() | () -> 42 |
IntConsumer | void accept(int) | n -> total += n (on a field) |
DoubleUnaryOperator | double applyAsDouble(double) | km -> 30 + km * 5 |
How nested classes and lambdas are compiled
- Nested classes become separate class files. The inner class gets a hidden constructor parameter for the outer object.
- Lambdas do not create class files at compile time. The body becomes a private method, and
invokedynamicwithLambdaMetafactorybuilds the object at runtime. - A non-capturing lambda (uses no local variables or
this) is usually created once and reused, so it is very cheap.
| Source | Generated file / code |
|---|---|
Member inner class Car.Engine | Car$Engine.class |
Static nested class Pizza.Builder | Pizza$Builder.class |
First local class LineItem in BillPrinter | BillPrinter$1LineItem.class |
First anonymous class in AnonymousDemo | AnonymousDemo$1.class |
Lambda in main | Private method like lambda$main$0 plus invokedynamic; no class file |
Inner classes and lambdas best practices
| Do | Do not |
|---|---|
| Prefer static nested classes by default | Make a class inner just because it is inside another |
| Use lambdas for one-method behaviour | Write anonymous classes for simple callbacks |
| Keep lambdas to one or two lines; extract a method otherwise | Put 20-line blocks inside a lambda |
| Use method references when they read clearly | Force a method reference that hides meaning |
Use meaningful parameter names: order -> order.total() | Use x, y, z everywhere |
Use built-in java.util.function interfaces | Create custom interfaces that duplicate Predicate or Function |
Add @FunctionalInterface on your own SAM interfaces | Accidentally add a second abstract method |
Use primitive interfaces like IntPredicate in hot loops | Box millions of numbers through Function<Integer, Integer> |
Tricky Interview Points
Q1) What is a nested class and what are its types?
Answer A class declared inside another class. Types: member inner class, static nested class, local class (inside a method), and anonymous class (no name).
Q2) What is the difference between an inner class and a static nested class?
Answer An inner class needs an outer object and holds a hidden reference to it, so it can use outer instance members directly. A static nested class needs no outer object and has no such reference.
Q3) How do you create an object of a member inner class from outside?
Answer First create the outer object, then use outer.new Inner(), for example Car.Engine e = car.new Engine();
Q4) How do you create an object of a static nested class?
Answer Directly with new Outer.Nested(), without any outer object.
Q5) Can an inner class access private members of the outer class?
Answer Yes. Nested classes can access all members of the outer class, including private ones, and the outer class can access private members of its nested classes.
Q6) What is Outer.this?
Answer Inside an inner class, Outer.this refers to the enclosing outer object. It is used when an inner member hides an outer member with the same name.
Q7) What is a local inner class?
Answer A class declared inside a method or block. It is visible only there and can use effectively final local variables and parameters.
Q8) What is an anonymous inner class?
Answer A class with no name that is declared and instantiated in one expression to implement an interface or extend a class once, for example a click listener.
Q9) Can an anonymous class have a constructor?
Answer No, because it has no name. It can use an instance initializer block and pass arguments to the superclass constructor.
Q10) What is a lambda expression?
Answer A short unnamed function introduced in Java 8 that implements the single abstract method of a functional interface, for example (a, b) -> a + b.
Q11) What is a functional interface?
Answer An interface with exactly one abstract method. It can have default and static methods. Examples: Runnable, Comparator, Predicate, Function.
Q12) What is the purpose of @FunctionalInterface?
Answer It documents the intent and makes the compiler report an error if the interface does not have exactly one abstract method.
Q13) Name the main functional interfaces in java.util.function.
Answer Predicate (test, returns boolean), Function (apply, converts), Consumer (accept, returns nothing), Supplier (get, takes nothing), UnaryOperator, BinaryOperator, and BiFunction.
Q14) Why must variables used in a lambda be effectively final?
Answer The lambda captures a copy of the value and may run later or on another thread. Allowing changes would make the copy and the variable disagree, so Java forbids reassignment.
Q15) What is the difference between a lambda and an anonymous class?
Answer A lambda targets only functional interfaces, has no state, does not create a new scope, and this refers to the enclosing object. An anonymous class can extend classes, override many methods, keep fields, and its this is the anonymous object.
Q16) What is a method reference? Name its kinds.
Answer A shorthand for a lambda that calls an existing method. Kinds: static (Integer::parseInt), particular object (System.out::println), arbitrary object of a type (String::toUpperCase), and constructor (ArrayList::new).
Q17) What does this mean inside a lambda?
Answer It refers to the object of the enclosing class, exactly as in the surrounding method. A lambda does not introduce its own this.
Q18) Can a lambda throw a checked exception?
Answer Only if the functional interface method declares it. Built-in ones like Function do not, so you must catch it inside the lambda, use a custom interface, or wrap it in an unchecked exception.
Q19) How can an inner class cause a memory leak?
Answer An inner object keeps a hidden reference to its outer object. If the inner object is stored long-term, the outer object cannot be garbage collected. Use static nested classes to avoid this.
Q20) Are lambdas compiled into separate class files?
Answer No. Anonymous classes produce files like Outer$1.class, but a lambda body becomes a private method and the object is created at runtime through invokedynamic.
Simple Programs
Bank account with an inner Transaction class
import java.util.ArrayList;
import java.util.List;
public class BankAccount {
private final String holder;
private double balance;
private final List<Transaction> history = new ArrayList<>();
BankAccount(String holder) {
this.holder = holder;
}
class Transaction { // inner: belongs to one account
private final String type;
private final double amount;
private final double balanceAfter;
Transaction(String type, double amount) {
this.type = type;
this.amount = amount;
this.balanceAfter = balance; // reads the outer field directly
}
@Override
public String toString() {
return holder + " | " + type + " " + amount + " | balance " + balanceAfter;
}
}
void deposit(double amount) {
balance += amount;
history.add(new Transaction("DEPOSIT", amount));
}
void withdraw(double amount) {
if (amount > balance) {
System.out.println("Insufficient funds for " + amount);
return;
}
balance -= amount;
history.add(new Transaction("WITHDRAW", amount));
}
public static void main(String[] args) {
BankAccount acc = new BankAccount("Asha");
acc.deposit(5000);
acc.withdraw(1200);
acc.withdraw(9000); // Insufficient funds for 9000.0
acc.history.forEach(System.out::println);
// Asha | DEPOSIT 5000.0 | balance 5000.0
// Asha | WITHDRAW 1200.0 | balance 3800.0
}
} Music playlist: static nested Node and inner Iterator
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Playlist implements Iterable<String> {
private static class Node { // static nested: needs no Playlist reference
final String song;
Node next;
Node(String song) {
this.song = song;
}
}
private Node head;
private Node tail;
void add(String song) {
Node n = new Node(song);
if (head == null) {
head = tail = n;
} else {
tail.next = n;
tail = n;
}
}
private class SongIterator implements Iterator<String> { // inner: reads head of this playlist
private Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public String next() {
if (current == null) throw new NoSuchElementException();
String song = current.song;
current = current.next;
return song;
}
}
@Override
public Iterator<String> iterator() {
return new SongIterator();
}
public static void main(String[] args) {
Playlist p = new Playlist();
p.add("Kesariya");
p.add("Naatu Naatu");
p.add("Jai Ho");
for (String song : p) {
System.out.println("Now playing: " + song);
}
}
} Button click listeners: anonymous class, lambda, and method reference
import java.util.ArrayList;
import java.util.List;
public class ButtonDemo {
interface ClickListener {
void onClick(String source);
}
static class Button {
private final String label;
private final List<ClickListener> listeners = new ArrayList<>();
Button(String label) {
this.label = label;
}
void addListener(ClickListener l) {
listeners.add(l);
}
void click() {
listeners.forEach(l -> l.onClick(label));
}
}
static void logClick(String source) {
System.out.println("[log] " + source + " clicked");
}
public static void main(String[] args) {
Button buy = new Button("Buy Now");
buy.addListener(new ClickListener() { // anonymous class
@Override
public void onClick(String source) {
System.out.println("Adding item to cart");
}
});
buy.addListener(source -> System.out.println("Showing offers")); // lambda
buy.addListener(ButtonDemo::logClick); // method reference
buy.click();
}
} Calculator using a map of lambdas
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
public class LambdaCalculator {
public static void main(String[] args) {
Map<String, BinaryOperator<Integer>> ops = new LinkedHashMap<>();
ops.put("+", (a, b) -> a + b);
ops.put("-", (a, b) -> a - b);
ops.put("*", (a, b) -> a * b);
ops.put("/", (a, b) -> b == 0 ? 0 : a / b);
ops.put("max", Math::max);
int x = 24;
int y = 6;
ops.forEach((symbol, op) ->
System.out.println(x + " " + symbol + " " + y + " = " + op.apply(x, y)));
// 24 + 6 = 30, 24 - 6 = 18, 24 * 6 = 144, 24 / 6 = 4, 24 max 6 = 24
}
} Sorting employees with Comparator lambdas
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class EmployeeSort {
record Employee(String name, String dept, double salary) { }
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Ravi", "IT", 85000),
new Employee("Asha", "HR", 60000),
new Employee("Kiran", "IT", 95000),
new Employee("Meena", "HR", 72000)
));
staff.sort(Comparator.comparing(Employee::name));
System.out.println("By name:");
staff.forEach(e -> System.out.println(" " + e.name()));
staff.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder()));
System.out.println("By department, highest salary first:");
staff.forEach(e -> System.out.println(" " + e.dept() + " " + e.name() + " " + e.salary()));
}
} Delivery charges with lambda strategies
import java.util.Map;
import java.util.function.DoubleUnaryOperator;
public class DeliveryCharges {
public static void main(String[] args) {
Map<String, DoubleUnaryOperator> plans = Map.of(
"STANDARD", km -> 30 + km * 5,
"EXPRESS", km -> 60 + km * 8,
"PRIME", km -> 0
);
double distance = 6;
for (String plan : new String[] { "STANDARD", "EXPRESS", "PRIME" }) {
System.out.println(plan + ": Rs." + plans.get(plan).applyAsDouble(distance));
}
// STANDARD: Rs.60.0, EXPRESS: Rs.108.0, PRIME: Rs.0.0
}
} Tea maker: chaining Consumers with andThen
import java.util.function.Consumer;
public class TeaMaker {
public static void main(String[] args) {
Consumer<StringBuilder> boilWater = cup -> cup.append("hot water");
Consumer<StringBuilder> addTea = cup -> cup.append(" + tea leaves");
Consumer<StringBuilder> addMilk = cup -> cup.append(" + milk");
Consumer<StringBuilder> addSugar = cup -> cup.append(" + sugar");
Consumer<StringBuilder> masalaChai = boilWater.andThen(addTea).andThen(addMilk).andThen(addSugar);
Consumer<StringBuilder> blackTea = boilWater.andThen(addTea);
StringBuilder cup1 = new StringBuilder();
masalaChai.accept(cup1);
StringBuilder cup2 = new StringBuilder();
blackTea.accept(cup2);
System.out.println("Chai: " + cup1); // hot water + tea leaves + milk + sugar
System.out.println("Black tea: " + cup2); // hot water + tea leaves
}
} Problem Solving Tricks
- Default to static nested classes. Make a class inner only when it truly needs the outer object.
- Create an inner object from outside with
outer.new Inner(); a static nested one withnew Outer.Nested(). - Use
Outer.this.fieldwhen an inner field hides an outer field with the same name. - Lambda = functional interface only. If you need two methods or fields, use an anonymous or named class.
- Inside a lambda,
thisis the enclosing object; inside an anonymous class,thisis the anonymous object. - Captured locals must be effectively final. Fields are not restricted.
- Remember the four helpers: Predicate tests, Function converts, Consumer uses, Supplier gives.
- If a lambda only calls one method, try a method reference:
s -> s.trim()becomesString::trim. - Keep lambdas short. If one grows beyond a few lines, move it into a named method.
- Use
removeIf,replaceAll,forEach,Map.merge, andComparator.comparingdaily: they are the easiest lambda wins.
Practice Programs List
- Create a
Universityclass with an innerDepartmentclass that prints the university name. - Write a
Laptopclass with a static nestedBuilderfor RAM, storage, and colour. - Use
Outer.thisto print an outer field hidden by an inner field with the same name. - Write a method with a local class
Studentthat calculates grades inside that method only. - Create an anonymous class that implements
Comparator<String>to sort names by length. - Rewrite the anonymous comparator as a lambda, then as
Comparator.comparing(String::length). - Write your own
@FunctionalInterfacecalledTaxCalculatorand implement GST and income tax with lambdas. - Use
Predicate,Function,Consumer, andSupplieronce each in a small program. - Show that reassigning a local variable used in a lambda gives a compile error.
- Print the value of
thisinside an inner class, an anonymous class, and a lambda. - Convert four lambdas into the four kinds of method references.
- Combine predicates with
and,or, andnegateto filter a list of products. - Build a calculator using
Map<String, BinaryOperator<Integer>>. - Implement a linked list with a static nested
Nodeand an innerIterator, then loop over it with for-each.