Alex Rivera | Logout

What is the point of using abstract methods?

Asked 2011-12-06T01:32:35.910
40

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 implement me", and if we forget them, the compiler throws an error?

Does it mean something else? I also read something about "we don't have to rewrite the same code", but in the abstract class, we only "declare" the abstract method, so we will have to rewrite the code in the child class.

Can you help me understand it a bit more? I checked the other topics about "abstract class/methods" but I didn't find an answer.

Edit
Report

1 Answer

-2

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)
    }
  }
}
answered 2011-12-06T01:38:37.540

Your Answer