简体   繁体   中英

How to let Subclass cover the inner class of the Class?

package tt;

class Out {
    class Inner {
        void print() {
            System.out.println("i anm inner1");
        }
    }

    public void run() {
        Inner in = new Inner();
        in.print();
    }

}

class Out2 extends Out{
    class Inner{
        void print() {
            System.out.println("i anm inner2");
        }
    }
}

public class Test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        new Out2().run(); // 打印 i anm inner2
    }
}

This program prints out ("i anm inner1") now. How can I make the program print("i anm inner2")?

Instead of covering the inner class you could cover (override) a factory method in the base class, you the Out2.Inner must extend the Out.Inner

class Out {

    class Inner {
            void print() {
                System.out.println("i anm inner1");
            }
    }

    public Inner createInner(){
        return new Inner();
    }

    public void run() {
        Inner in = createInner();
        in.print();
    }

}

class Out2 extends Out {

    class Inner extends Out.Inner {
            void print() {
                System.out.println("i anm inner2");
            }

    }

    public Out.Inner createInner(){
        return new Inner();
    }
}

Either call the print() of the child's inner class

new Out2().new Inner().print(); 

Or, override run() inside Out2

    @Override
    public void run() {
        Inner in = new Inner();
        in.print();
    }

您应该在out2覆盖run()

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