Java 有什么方法可以实例化匿名内部类吗?
有没有办法从main方法访问匿名类的方法?Java 有什么方法可以实例化匿名内部类吗?,java,inner-classes,Java,Inner Classes,有没有办法从main方法访问匿名类的方法? 如果是,访问这种方法的语法是什么?匿名类将在您需要它们的同时实例化。他们没有名字。如果您使用Swing或小程序进行了编码,那么实际上存在匿名实例化的ActionListeners或EventHandler如果您至少有一个匿名类实例(对象),首先看起来是: class Demo { void show() { System.out.println("i am in show method of super class"); } }
如果是,访问这种方法的语法是什么?匿名类将在您需要它们的同时实例化。他们没有名字。如果您使用Swing或小程序进行了编码,那么实际上存在匿名实例化的
ActionListeners或EventHandler
如果您至少有一个匿名类实例(对象),首先看起来是:
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
public class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d2 = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d2.show();
try {
Demo v = d2.getClass().newInstance();
System.out.println("Object created"+v.getClass().getTypeName()); // Canonical is null
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我很惊讶,匿名cls似乎是静态类型,不需要对父级的隐藏引用?似乎没有。请说明您遇到问题的代码是什么?检查此链接可能会发现:@Soorapadman link对您有一个有效的答案感谢此链接,但是为什么不可能访问不被外部类的方法覆盖的匿名类的方法呢?这里有几个重要的词:匿名类、内部类、静态类,必须是精确的。你们在题目上写不同的问题,在正文上写不同的问题