Java Anonymous Classes
In this chapter you will learn:
- What is Java Anonymous Classes
- How to define an anonymous class
- Example - declares and instantiates an anonymous class that implements an interface
Description
An anonymous class is a class without a name and simultaneously declared. You can instantiate an anonymous class where it is legal to specify an expression.
An anonymous class instance can only access local final variables and final parameters.
Syntax
How to define an anonymous class?
abstract class People {
abstract void speak();
}//from ww w . ja va 2 s . c om
public class Main {
public static void main(final String[] args) {
new People() {
String msg = "test";
@Override
void speak() {
System.out.println(msg);
}
}.speak();
}
}
The code above generates the following result.
Example
The following code declares and instantiates an anonymous class that implements an interface.
interface People {
abstract void speak();
}/*from w w w .j av a 2s .co m*/
public class Main {
public static void main(final String[] args) {
new People() {
String msg = (args.length == 1) ? args[0] : "nothing to say";
@Override
public void speak() {
System.out.println(msg);
}
}.speak();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to define a local class
- Example - Java Local Classes
- How to create a local class and return it from a method
Java Class
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files
Java Object
Java Object Reference Variable
Java Methods
Java Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local ClassesJava Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files