Force invocation of base class method

后端 未结 4 1205
孤城傲影
孤城傲影 2020-12-12 00:11

The following code when run obviously prints out \"B1/A2/B2\". Now, is it possible for it to print \"A1/A2/B2\" instead (i.e. A#method2() should invoke method1() on A, not

4条回答
  •  攒了一身酷
    2020-12-12 00:48

    Yes, you can do it. Define A in package a:

    package a;
    public class A {
        void method1() {
            System.out.println("A1");
        }
        public void method2() {
            method1();
            System.out.println("A2");
        }
    }
    

    Define B in package b:

    package b;
    import a.A;
    public class B extends A {
        @Override public void method2() {
            super.method2();
            System.out.println("B2");
        }
        void method1() {
            System.out.println("B1");
        }
    }
    

    Put your test in package a and run it. The result is A1/A2/B2. Of course this is unhealthy: note the necessary omission of @Override on method1 - if you put it back in, you will get a compiler error:

    method does not override or implement a method from a supertype
    

提交回复
热议问题