所以我有一个父类说A和A的内部类叫做I.我正在调用一个函数,即pop(),它是A类。现在这个pop()被B覆盖,这是A的孩子。
现在当从I调用pop时,将弹出A执行或B ??
package testers;
public class test
{
public void run()
{
System.out.println("Inside test");
}
public void irun()
{
InnerClassOne o=new InnerClassOne();
o.inside();
System.out.println("Inside irun");
}
private void inside()
{
// TODO Auto-generated method stub
}
class InnerClassOne
{
void inside()
{
System.out.println("Inside inner");
test.this.run();
}
}
}
package testers;
public class test2 extends test
{
public void run()
{
System.out.println("Overriden");
}
public static void main(String []args)
{
test t1= new test();
t1.irun();
}
}
答案 0 :(得分:0)
这完全取决于你如何创建新的实例。我们假设我们有以下几个类:
public class Test {
public void print() {
System.out.println("Hi");
}
public class TestInner {
public void doSomething() {
print();
}
}
}
public class Test2 extends Test {
@Override
public void print() {
System.out.println("Bye");
}
}
...
public class Main {
public static void main(String[] args) {
Test t1 = new Test();
Test.TestInner testInner1 = t1.new TestInner();
Test2 t2 = new Test2();
Test2.TestInner testInner2 = t2.new TestInner();
System.out.println("Test inner 1 doSomething: ");
testInner1.doSomething();
//Prints 'Hi'
System.out.println("Test inner 2 doSomething: ");
testInner2.doSomething();
//Prints 'Bye'
}
}
如果您创建了Test
或Test2
的实例,那么它只是调用外部类的print
函数。
当您转向TestInner
或Test
课程时,您可能会看到一些意外行为:
public class Main {
public static void main(String[] args) {
Test t1 = new Test();
Test.TestInner testInner1 = t1.new TestInner();
Test2 t2 = new Test2();
Test2.TestInner testInner2 = t2.new TestInner();
Test.TestInner testInner3 = (Test.TestInner) testInner2;
System.out.println("Test inner 3 (cast inner) doSomething: ");
testInner3.doSomething();
//Prints 'Bye'
Test t3 = (Test) t2;
Test.TestInner testInner4 = t3.new TestInner();
System.out.println("Test inner 4 (cast wrapper class) doSomething: ");
testInner4.doSomething();
//Prints 'Bye'
}
}
即使我们明确表达了testInner3
(内部类)和testInner4
(外部类),它仍会打印出Bye。这是因为当您将对象转换为另一种类型时,您只需使用其他类型引用它。对象的实际类型不会更改。