簡體   English   中英

如果我在父類中調用父類的方法,它是否會調用同名的子類方法

[英]If I invoke a parent's method in parent class, does it invoke child class method with the same name

我想知道調用父類方法的子類是否會調用父類中的重載方法,是否會調用子類中的重載方法

class Parent {

    void doStuff() {

    }

    void asd() {
        doStuff();
    }
}

class Child extends Parent {
    void doStuff() {
        // implementation
    }
}

static void main(Args... args) {
    new Child().asd(); -> does this invoke the doStuff with the implementation or the empty doStuff in the parent class?
}
class Parent{
    void doStuff(){
       System.out.println("parent class");
    }
    void asd(){
    doStuff();
    }
 }
 class Child extends Parent(){

       @Override
       void doStuff(){
         //super.asd();
         System.out.println("child class");
    }
 }

/** * 當您運行程序時,您將看到兩個方法被調用 * 一個來自父類,然后是子類的覆蓋方法。 * 只需取消注釋 childs doStuff() 中的 super.asd() 即可看到兩個打印。 **/

public static void main(String [] args){
    Child c = new Child();
    c.doStuff();  // call methods
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM