Java中的调用方法,低音类

时间:2018-12-07 09:35:50

标签: java

我有三个具有三种相同方法的类:

 public void someMethod()

现在,我得到了A的父亲BC的儿子B。它是这样的:A-B-C。 我的问题是如何从someMethod()调用方法C?那么父/基类中的方法将被执行吗?

我不确定答案,但是我认为这不可能吗?我的意思是,如果我执行super.someMethod(),它将调用B的方法,因为BC的父亲吗?

3 个答案:

答案 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

注意


  1. 在类C中,不存在属于B或A的someMethod,它被覆盖。只是一种方法。
  2. 使用super关键字,您可以从其直接父类而不是继承树的顶级类中调用方法。