package tt;
class Out {
class Inner {
void print() {
System.out.println("i anm inner1");
}
}
public void run() {
Inner in = new Inner();
in.print();
}
}
class Out2 extends Out{
class Inner{
void print() {
System.out.println("i anm inner2");
}
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
new Out2().run(); // 打印 i anm inner2
}
}
此程序现在打印出来(“我anm inner1”)。 如何打印程序(“我anm inner2”)?
答案 0 :(得分:2)
您可以覆盖(覆盖)基类中的工厂方法,而不是覆盖内部类,而Out2.Inner必须扩展Out.Inner
class Out {
class Inner {
void print() {
System.out.println("i anm inner1");
}
}
public Inner createInner(){
return new Inner();
}
public void run() {
Inner in = createInner();
in.print();
}
}
class Out2 extends Out {
class Inner extends Out.Inner {
void print() {
System.out.println("i anm inner2");
}
}
public Out.Inner createInner(){
return new Inner();
}
}
答案 1 :(得分:1)
调用孩子内部班级的print()
new Out2().new Inner().print();
或者,覆盖run()
Out2
@Override
public void run() {
Inner in = new Inner();
in.print();
}
答案 2 :(得分:0)
您应该覆盖run()
out2