Java: Calling a super method which calls an overridden method

前端 未结 13 2318
有刺的猬
有刺的猬 2020-11-27 10:29
public class SuperClass
{
    public void method1()
    {
        System.out.println(\"superclass method1\");
        this.method2();
    }

    public void method2(         


        
13条回答
  •  春和景丽
    2020-11-27 10:53

    If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.

    Here's a suggestion:

    public class SuperClass {
    
      public void method1() {
        System.out.println("superclass method1");
        this.internalMethod2();
      }
    
      public void method2()  {
        // this method can be overridden.  
        // It can still be invoked by a childclass using super
        internalMethod2();
      }
    
      private void internalMethod2()  {
        // this one cannot.  Call this one if you want to be sure to use
        // this implementation.
        System.out.println("superclass method2");
      }
    
    }
    
    public class SubClass extends SuperClass {
    
      @Override
      public void method1() {
        System.out.println("subclass method1");
        super.method1();
      }
    
      @Override
      public void method2() {
        System.out.println("subclass method2");
      }
    }
    

    If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).

提交回复
热议问题