我有三个具有三种相同方法的类:
public void someMethod()
现在,我得到了A
的父亲B
和C
的儿子B
。它是这样的:A
-B
-C
。
我的问题是如何从someMethod()
调用方法C
?那么父/基类中的方法将被执行吗?
我不确定答案,但是我认为这不可能吗?我的意思是,如果我执行super.someMethod()
,它将调用B
的方法,因为B
是C
的父亲吗?
答案 0 :(得分:0)
当子类具有与父类相同的名称和参数的方法时,它将调用覆盖。覆盖方法可以使用super
调用父方法:
class A {
public void foo() {
System.out.println("A:foo()");
}
public void bar() {
System.out.println("A:bar()");
}
}
class B extends A {
public void foo() {
System.out.println("B:foo()");
}
public void bar() {
super.bar();
System.out.println("B:bar()");
}
}
class C extends B {
public void foo() {
System.out.println("C:foo()");
}
public void bar() {
super.bar();
System.out.println("C:bar()");
}
}
这是测试方法:
C c = new C();
c.foo();
System.out.println();
c.bar();
输出:
C:foo()
A:bar()
B:bar()
C:bar()
答案 1 :(得分:0)
有两种情况:
B类替代 A类的方法:在这种情况下,您不能从C类调用为A类的方法 B没有公开这样做的方法。
B类不会覆盖:A类的方法:当您调用super.someMethod()
时,您正在B类中调用someMethod,但是它并未被覆盖,因此正在调用A类的实现。
答案 2 :(得分:0)
希望您会得到答案。
class A {
public String someMethod() {
return "someMethod in A";
}
}
class B extends A{
public String someMethod() {
System.out.println("Calling to B -> " + super.someMethod());
return "someMethod in B";
}
}
class C extends B{
public String someMethod() {
System.out.println("Calling to C -> " + super.someMethod());
return "someMethod in C";
}
}
public class Test {
public static void main (String[] args) {
C c = new C();
System.out.println("calling overridden someMethod -> " + c.someMethod());
B b = new B();
System.out.println("calling overridden someMethod -> " + b.someMethod());
A a = new A();
System.out.println("calling overridden someMethod -> " + a.someMethod());
B bc = new C();
System.out.println("calling overridden someMethod -> " + bc.someMethod());
A ab = new B();
System.out.println("calling overridden someMethod -> " + ab.someMethod());
}
}
结果
Calling to B -> someMethod in A
Calling to C -> someMethod in B
calling overridden someMethod -> someMethod in C
Calling to B -> someMethod in A
calling overridden someMethod -> someMethod in B
calling overridden someMethod -> someMethod in A
Calling to B -> someMethod in A
Calling to C -> someMethod in B
calling overridden someMethod -> someMethod in C
Calling to B -> someMethod in A
calling overridden someMethod -> someMethod in B
注意