Java – abstract and anonymous classes
•
Java
See English answers > Creating the instance of abstract class or anonymous class 8
abstract class Two {
Two() {
System.out.println("Two()");
}
Two(String s) {
System.out.println("Two(String");
}
abstract int display();
}
class One {
public Two two(String s) {
return new Two() {
public int display() {
System.out.println("display()");
return 1;
}
};
}
}
class Ajay {
public static void main(String ...strings ){
One one=new One();
Two two=one.two("ajay");
System.out.println(two.display());
}
}
We can't instantiate an abstract class, so why can function two (string s) create an instance of an abstract class, two????
Solution
It does not create an instance of abstract 2 It creates a concrete anonymous class that extends two and instantiates it
It is almost equivalent to using such a named inner class:
class One {
public Two two(String s) {
return new MyTwo();
}
class MyTwo extends Two {
public int display() {
System.out.println("display()");
return 1;
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
