Java: Calling a super method which calls an overridden method

前端 未结 13 2351
有刺的猬
有刺的猬 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 11:10

    Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:

    class Base 
    {
        public void method2()
        {
            System.out.println("superclass method2");
        }
    }
    
    class SuperClass extends Base
    {
        public void method1()
        {
            System.out.println("superclass method1");
            super.method2();
        }
    }
    
    class SubClass extends SuperClass
    {
        @Override
        public void method1()
        {
            System.out.println("subclass method1");
            super.method1();
        }
    
        @Override
        public void method2()
        {
            System.out.println("subclass method2");
        }
    }
    
    public class Demo 
    {
        public static void main(String[] args) 
        {
            SubClass mSubClass = new SubClass();
            mSubClass.method1();
        }
    }
    

    Output:

    subclass method1
    superclass method1
    superclass method2
    

提交回复
热议问题