作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题在这里已经有了答案:
Can we instantiate an abstract class?
(16 个答案)
8年前关闭。
当我创建一个抽象类的对象时,我必须像接口(interface)一样这样做。
AbstractClass abstractClass = new AbstractClass() {
@Override
public void abstractMethod() {
}
};
AbstractClass
的对象是匿名内部类对象吗?
最佳答案
AbstractClass abstractClass = new AbstractClass() {
@Override
public void abstractMethod() {
}
};
AbstractClass
的匿名类。 .您也可以对接口(interface)使用相同的符号。
SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/};
SomeInterface
的类。 .
class Anonymous {
public void someMethod(){
System.out.println("This is from Anonymous");
}
}
class TestAnonymous{
// this is the reference of superclass
Anonymous a = new Anonymous(){ // anonymous class definition starts here
public void someMethod(){
System.out.println("This is in the subclass of Anonymous");
}
public void anotherMethod(){
System.out.println("This is in the another method from subclass that is not in suprerclass");
}
}; // and class ends here
public static void main(String [] args){
TestAnonymous ta = new TestAnonymous();
ta.a.someMethod();
// ta.a.anotherMethod(); commented because this does not compile
// for the obvious reason that we are using the superclass reference and it
// cannot access the method in the subclass that is not in superclass
}
}
This is in the subclass of Anonymous
anotherMethod
在作为匿名类创建的子类中实现。和
a
是
Anonymous
类型的引用变量即匿名类的父类(super class)。所以声明
ta.a.anotherMethod();
编译器错误为
anotherMethod()
在
Anonymous
中不可用.
关于java - 抽象类的对象是匿名内部类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787445/
我是一名优秀的程序员,十分优秀!