A class in which a class definition and instantiation are described in a single expression without specifying a class name. Interface implementation / method retrieval, class inheritance / override / method retrieval can be performed without specifying a class name, which is convenient when you want to use a method only on the spot.
interface Inter{
void methodA();
}
class SuperT{
void methodS() {
System.out.println("Super");
}
}
class OuterT{ //Outer class
void method1() {
new Inter() { //Implement and instantiate the interface at the same time
public void methodA() {
System.out.println("methodA implementation");
}
}.methodA(); //Call methodA from the instantiated one
}
/*void method2() {
new SuperT() {
void methodS() {
System.out.println("Override");
}
}.methodS();
}*/
}
public class Tokumei {
public static void main(String[] args) {
OuterT ot = new OuterT();
ot.method1();
//ot.method2();
System.out.println("-----When called after assigning to a SuperT type variable-----");
SuperT st = new SuperT() { //Assign to a superclass type variable
void methodS() {
System.out.println("Override");
}
void methodSub() { //Anonymous subclass proprietary method
System.out.println("Sub");
}
};
st.methodS();
//st.methodSub(); //You cannot call methods unique to anonymous subclasses with superclass variables
System.out.println("-----When called directly from an object-----");
new SuperT() {
void methodS() {
System.out.println("Override");
}
void methodSub() {
System.out.println("Sub");
}
}.methodSub(); //Can be called directly
}
}
methodA implementation
-----When called after assigning to a SuperT type variable-----
Override
-----When called directly from an object-----
Sub
(1) When inheriting a class, anonymous subclasses can override methods.
(2) When calling after assigning an anonymous subclass that inherits a superclass to a variable of superclass type, only the methods (including overridden ones) in the superclass can be called. (The mechanism is the same as for normal superclasses and subclasses, and the accessible range changes depending on the variable type.)
(3) When calling directly from an object, the method set independently in the anonymous subclass can also be called.
Recommended Posts