簡體   English   中英

子類和方法-如何從子類調用方法?

[英]subclass and method-How can i call a method from a subclass?

在此處輸入圖片說明

如何從子類調用方法?

希望以下內容能解開你的疑惑:

class SuperA {
    void superMeth1() {
        System.out.println("superMeth1");
    }

    void superMeth2() {
        System.out.println("superMeth2");
    }
}

class Sub1 extends SuperA {
    void superMeth1() {
        System.out.println("superMeth1_sub1");
    }

    void sub1Meth1() {
        System.out.println("subMeth1");
    }
}

public class Main {
    public static void main(String[] args) {
        SuperA obj = new SuperA();
        obj.superMeth1(); // Prints superMeth1
        obj.superMeth2(); // Prints superMeth2

        obj = new Sub1();
        obj.superMeth1(); // Prints superMeth1_sub1
        //obj.sub1Meth1(); // Compilation error as SuperA does not know about Sub1
        ((Sub1) obj).sub1Meth1(); // Prints subMeth1 because of the cast

        Sub1 sub1 = new Sub1();
        sub1.superMeth1(); // Prints superMeth1_sub1
        sub1.sub1Meth1(); // Prints subMeth1
    }
}

暫無
暫無

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

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