Skip to main content

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.

L1

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 Car has an Engine. An engine made for that car has no meaning on its own, so Engine lives inside Car.
  • The compiler creates a separate .class file for each nested class, such as Car$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

TypeDeclaredNeeds outer object?Can use outer instance members?How to createReal life
Member inner classInside the class, outside methodsYesYes, even privateouter.new Inner()Engine of a specific car
Static nested classInside the class with staticNoOnly through an object referencenew Outer.Nested()Builder that creates a pizza
Local classInside a method or blockOnly in instance methodsYes, plus effectively final localsnew Local() inside that methodA helper hired for one task only
Anonymous classInside an expression, no nameSame as localYes, plus effectively final localsnew 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, plain new Inner() works in instance methods.
  • If names clash, use Outer.this.field to 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 static inside another class. It does not hold a reference to an outer object, so you create it with new 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

PointMember inner classStatic nested class
KeywordNo staticstatic
Outer object needed?YesNo
Hidden reference to outerYes (Outer.this)No
Access to outer instance fieldsDirectOnly through an object reference
Access to outer static fieldsDirectDirect
Creation from outsideouter.new Inner()new Outer.Nested()
MemoryKeeps the outer object aliveLighter, no extra reference
Typical useIterator over the outer dataBuilder, Node, Entry, helpers
Real lifeEngine of one specific carA 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() { ... } or new 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, and Comparator chains.
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

FormExampleMeaning
No parameters() -> System.out.println("Hi")Runnable-style action
One parametern -> n * 2Parentheses optional for one untyped parameter
Two parameters(a, b) -> a + bParentheses required
Typed parameters(int a, int b) -> a + bTypes written explicitly
var parameters (Java 11)(var a, var b) -> a + bAllows annotations on parameters
Block body(a, b) -> { int s = a + b; return s; }Braces need return for a value
Expression bodys -> 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 default and static methods, and methods from Object such as equals do not count.
  • Add @FunctionalInterface so 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.
InterfaceMethodTakes / returnsExampleReal life
Predicate<T>test(T)T to booleanage -> age >= 18Is this person eligible to vote?
Function<T, R>apply(T)T to Rs -> s.length()Convert rupees to dollars
Consumer<T>accept(T)T to nothingmsg -> send(msg)Send an SMS
Supplier<T>get()nothing to T() -> generateOtp()OTP generator
UnaryOperator<T>apply(T)T to Ts -> s.toUpperCase()Apply a filter to a photo
BinaryOperator<T>apply(T, T)T, T to T(a, b) -> a + bAdd two bills
BiFunction<T, U, R>apply(T, U)T, U to R(price, qty) -> price * qtyPrice times quantity
BiConsumer<T, U>accept(T, U)T, U to nothing(k, v) -> print(k, v)Print a name and phone number
Runnablerun()nothing to nothing() -> backup()Start a backup job
Comparator<T>compare(T, T)T, T to int(a, b) -> a.price - b.priceSort 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 final keyword.
  • 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 this or 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::method or object::method.
  • Real life: instead of explaining the whole recipe, you say "follow page 42 of the cookbook".
KindSyntaxExampleEquivalent lambda
Static methodClass::staticMethodInteger::parseInts -> Integer.parseInt(s)
Instance method of a particular objectobject::methodSystem.out::printlnx -> System.out.println(x)
Instance method of an arbitrary objectClass::instanceMethodString::toUpperCases -> s.toUpperCase()
ConstructorClass::newArrayList::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

PointAnonymous classLambda
Target typeAny interface or class (abstract or concrete)Only a functional interface
Number of methodsCan override many methodsImplements exactly one method
State (fields)Can declare its own fieldsCannot declare fields
Meaning of thisThe anonymous object itselfThe enclosing class object
New scopeYes: can redeclare local variable namesNo: shares the enclosing method scope
Class fileCreates Outer$1.classNo extra class file; created at runtime with invokedynamic
Code lengthLongShort
Use whenSeveral methods, state, or extending a classSimple one-method behaviour
L2

Advanced — Inner Classes & Lambdas

this and Outer.this in inner classes, anonymous classes, and lambdas

  • In an inner class, this is the inner object and Outer.this is the enclosing object.
  • In an anonymous class, this is the anonymous object, so outer fields with the same name need Outer.this.
  • In a lambda, this means the enclosing object. A lambda does not introduce a new this.
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

SituationInner / anonymous classLambda
Declare a local with the same name as an enclosing localAllowed (shadows it)Compile error: already defined
Parameter with the same name as an enclosing localAllowedCompile error
Change an enclosing localNot allowedNot allowed
Change an enclosing fieldAllowedAllowed
Reach a hidden outer fieldOuter.this.fieldthis.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 this only when they use an instance member; otherwise they keep no outer reference.
  • Rule: make nested classes static unless 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 have forEach, merge, computeIfAbsent, getOrDefault.
  • Comparator.comparing(...), thenComparing(...), and reversed() 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

  • Predicate has and, or, negate, and Predicate.not(...) (Java 11) to combine conditions.
  • Function has andThen (run this, then the next) and compose (run the other first). Consumer also has andThen.
  • Comparator has thenComparing, reversed, nullsFirst, and nullsLast.
  • 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 Function and Consumer do not declare checked exceptions, so a lambda calling a method that throws IOException will 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 an Integer object. Primitive versions avoid boxing and are faster in loops and streams.
InterfaceMethodExample
IntPredicateboolean test(int)n -> n % 2 == 0
IntFunction<R>R apply(int)n -> "Table " + n
ToIntFunction<T>int applyAsInt(T)String::length
IntUnaryOperatorint applyAsInt(int)n -> n * n
IntBinaryOperatorint applyAsInt(int, int)Math::max
IntSupplierint getAsInt()() -> 42
IntConsumervoid accept(int)n -> total += n (on a field)
DoubleUnaryOperatordouble 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 invokedynamic with LambdaMetafactory builds 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.
SourceGenerated file / code
Member inner class Car.EngineCar$Engine.class
Static nested class Pizza.BuilderPizza$Builder.class
First local class LineItem in BillPrinterBillPrinter$1LineItem.class
First anonymous class in AnonymousDemoAnonymousDemo$1.class
Lambda in mainPrivate method like lambda$main$0 plus invokedynamic; no class file

Inner classes and lambdas best practices

DoDo not
Prefer static nested classes by defaultMake a class inner just because it is inside another
Use lambdas for one-method behaviourWrite anonymous classes for simple callbacks
Keep lambdas to one or two lines; extract a method otherwisePut 20-line blocks inside a lambda
Use method references when they read clearlyForce a method reference that hides meaning
Use meaningful parameter names: order -> order.total()Use x, y, z everywhere
Use built-in java.util.function interfacesCreate custom interfaces that duplicate Predicate or Function
Add @FunctionalInterface on your own SAM interfacesAccidentally add a second abstract method
Use primitive interfaces like IntPredicate in hot loopsBox millions of numbers through Function<Integer, Integer>
L3

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.

L4

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
    }
}
L5

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 with new Outer.Nested().
  • Use Outer.this.field when 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, this is the enclosing object; inside an anonymous class, this is 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() becomes String::trim.
  • Keep lambdas short. If one grows beyond a few lines, move it into a named method.
  • Use removeIf, replaceAll, forEach, Map.merge, and Comparator.comparing daily: they are the easiest lambda wins.
L6

Practice Programs List

  1. Create a University class with an inner Department class that prints the university name.
  2. Write a Laptop class with a static nested Builder for RAM, storage, and colour.
  3. Use Outer.this to print an outer field hidden by an inner field with the same name.
  4. Write a method with a local class Student that calculates grades inside that method only.
  5. Create an anonymous class that implements Comparator<String> to sort names by length.
  6. Rewrite the anonymous comparator as a lambda, then as Comparator.comparing(String::length).
  7. Write your own @FunctionalInterface called TaxCalculator and implement GST and income tax with lambdas.
  8. Use Predicate, Function, Consumer, and Supplier once each in a small program.
  9. Show that reassigning a local variable used in a lambda gives a compile error.
  10. Print the value of this inside an inner class, an anonymous class, and a lambda.
  11. Convert four lambdas into the four kinds of method references.
  12. Combine predicates with and, or, and negate to filter a list of products.
  13. Build a calculator using Map<String, BinaryOperator<Integer>>.
  14. Implement a linked list with a static nested Node and an inner Iterator, then loop over it with for-each.