What is the point of using abstract methods?

前端 未结 7 1476
春和景丽
春和景丽 2020-12-13 06:28

What\'s the point of using \"abstract methods\"? An abstract class cannot be instantiated, but what about the abstract methods? Are they just here to say \"you have to imple

7条回答
  •  天命终不由人
    2020-12-13 07:08

    Abstract methods must be overriden by any subclass that will not be abstract.

    So, for example you define an abstract class Log and you force the subclasses to override that method:

    public abstract class Log{
      public void logError(String msg){
        this.log(msg,1)
      }
      public void logSuccess(String msg){
        this.log(msg,2)
      }
      public abstract void log(String msg,int level){}
    }
    
    public class ConsoleLog{
      public void log(String msg,int level){
        if(level=1){
           System.err.println(msg)
        }else{
           System.out.println(msg)
        }
      }
    }
    

提交回复
热议问题