简体   繁体   中英

subclass and method-How can i call a method from a subclass?

在此处输入图片说明

How can i call a method from a subclass?

I hope the following will clarify your doubts:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM