Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • ANONYMOUS INNER CLASS THAT EXTENDS A CLASS:
  • ANONYMOUS INNER CLASS THAT IMPLEMENTS AN INTERFACE:
  • HOW TO ACCESS ADDITIONAL MEMBERS IN ANONYMOUS CLASSES:
  • ANONYMOUS CLASS DEFINED WITHIN A METHOD :

Was this helpful?

  1. 3) Inner Classes

3.3) Anonymous inner class

Previous3.2) Inner class (also called member class)Next3.4) Method local inner classes

Last updated 5 years ago

Was this helpful?

As the name implies, an anonymous inner class isn’t defined using an explicit name. An anonymous inner class is created when you combine instance creation with inheriting a class or implementing an interface. Anonymous classes come in handy when you wish to override methods for only a particular instance. They save you from defining new classes. The anonymous class might override none, few, or all methods of the inherited class. It must implement all methods of an implemented interface. The newly created object can be assigned to any type of variable—static variable, instance variable, local variable, method parameter, or returned from a method. Let’s start with an example of an anonymous inner class that extends a class.

ANONYMOUS INNER CLASS THAT EXTENDS A CLASS:

package com.gs.corejava.innerclasses;

class Pen {
	public void write() {
		System.out.println("Pen - write");
	}
}

class Montex extends Pen {
	public void write() {
		System.out.println("Montex - write");
	}

	public void price() {
		System.out.println("Only I can decide");
	}
}

public class Lecture {
	public static void main(String[] args) {
		Pen pen = new Montex();
		pen.write();
	}

}

Let’s replace this usual object instantiation by overriding method write, while instantiating Pen. To override method write() for this particular instance, we insert a class definition between () and ; (() and ; are in bold):

package com.gs.corejava.innerclasses;

class Pen {
	public void write() {
		System.out.println("Pen - write");
	}
}

public class Lecture {
	public static void main(String[] args) {
		Pen pen = new Pen() {
			public void write() {
				System.out.println("Montex - write");
			}

			public void price() {
				System.out.println("Only I can decide");
			}
		};
		pen.write();
	}

}

Example :

package com.gs.corejava.innerclasses;

class Pen {
	public void write() {
		System.out.println("Pen - write");
	}
}

public class Student {
	void attendLecture(Pen pen) {
		Lecture lecture = new Lecture();
		lecture.notes(pen);
	}

	public static void main(String[] args) {
		Student student = new Student();
		student.attendLecture(new Pen() {
			public void write() {
				System.out.println("I am writing");
			}
		});
	}
}

class Lecture {
	void notes(Pen pen) {
		pen.write();
	}
}

ANONYMOUS INNER CLASS THAT IMPLEMENTS AN INTERFACE:

Until now, you should have read that you can’t instantiate interfaces; you can’t use the keyword new with an interface. Think again. Examine the following code, in which the class BirdSanctuary instantiates the interface Flyable by using the keyword new:

Don’t worry; you’ve been reading correctly that you can’t use the operator new with an interface. The catch in the preceding code is that bird refers to an object of an anon- ymous inner class, which implements the interface Flyable.

The anonymous class used to instantiate an interface in the preceding code saved you from creating a class beforehand, which implemented the interface Flyable.

An anonymous inner class can extend at most one class or implement one interface. Unlike other classes, an anonymous class can neither implement multiple interfaces, nor extend a class and implement an interface together.

HOW TO ACCESS ADDITIONAL MEMBERS IN ANONYMOUS CLASSES:

By using an anonymous class, you can override the methods from its base class or implement the methods of an interface. You can also define new methods and vari- ables in an anonymous class (in bold):

You can’t call the additional member, method hungry(), using the reference variable bird. Why? The type of the reference variable bird is Flyable. So the variable bird can access only the members defined in interface Flyable. The variable bird can’t access additional methods and variables that are defined in anonymous classes that implement it.

ANONYMOUS CLASS DEFINED WITHIN A METHOD :

When an anonymous inner class is defined within a method, it can access only the final variables of the method in which it’s defined. This is to prevent reassignment of the variable values by the inner class. Examine the following example.

The code at 1 will compile if ingredient is modified to be defined as a final local variable.