An abstract class in Java need not implement any methods from its implementing interface. Why?

前端 未结 5 1086
星月不相逢
星月不相逢 2021-02-04 14:08

Let\'s look at the following simple code snippet in Java.

interface Sum
{
    abstract public void showSum();
}

interface Mul
{
    abstract public void showMul         


        
5条回答
  •  滥情空心
    2021-02-04 14:36

    The abstract class is not real implementation class. It may contain abstract methods and doesnot need to implement the methods from the interface. It is concern of the REAL implementing class to define the abstract/interface methods.

    See this difference between abstract class and interface

    Interface:
    public interface InterfaceClass {
        void interfaceMethod();
        //no method definition
    }
    
    
    //Abstract Class implementing InterfaceClass
    abstract class AbsClass implements InterfaceClass{
        abstract void abstractMethod();
        public void doSomethingCommon() {
            System.out.println("Abstract class may contain method definition");
        }
        //no need to implement methods of InterfaceClass because AbsClass is abstract
    }
    

    And here is real class that extends AbsClass: Its duty of RealClass to define all abstract methods and interface methods. Additionally, it may override the defined methods in abstract class as well.

    public class RealClass extends AbsClass{
        @Override
        public void interfaceMethod() {
            //implement interface method here
        }
        @Override
        void abstractMethod() {
        }
        // you may override the doSomethingCommon() of AbsClass too
        @Override
        public void doSomethingCommon() {
            // TODO Auto-generated method stub
            super.doSomethingCommon();
        }
    }
    

    Why there is no compile time error on AbsClass: We cannot create instances of abstract class. That's why there is no meaning of displaying error at compile time.

提交回复
热议问题