0

Edit: the difference between my question and What are the differences between abstract classes, interfaces, and when to use them, What are abstract classes and abstract methods? is that the chosen answers didn't mention about the compiler-warning part. One even mention the re-use of code by inheritance, which is bad practice actually.

I think what I want to know is beyond the language chosen. But, whatsoever, I means the abstract method in Java. From the documentation of Oracle:

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon).

But what I really want to know is the real purpose of it, not just the semantic rules.

For me, the purpose is that the compiler will tell me what I need to do in the future. Take Eclipse as an example, when I derive a subclass from a abstract class, Eclipse will help me to add all un-implemented methods by one click.

From another point of view, an abstract method will make the super-class-version method, which may have a basic functionality, no longer available, they're overridden.(I get this conclusion from decorator pattern.)

Still, all of the above is from my intuition. Any advice is appreciated.

1

2 Answers 2

2

No, the purpose is this:

public void clientMethod(AbstractType param){
    param.abstractMethod();
}

This code is using the abstract method without having to know anything about how it's implemented or which class implements it.

The typical example would be the Comparable interface, which contains the compareTo() method. This allows, for example, Arrays.sort() to implement a sort algorithm without having to know anything about what it is that it's sorting - just that the abstract method from the interface is implemented.

0

A virtual method can be overridden by a subclass if it chooses to, but it doesn't have to. The base class provides a "default" implementation.

An abstract method must be overridden by a subclass because the base class cannot or does not provide that "default" implementation.

abstract class Person 
{ 
   public string introduction() 
   {
      "I am a " + getSpecies() + " called " + getName() + "."; 
   }

   protected string getSpecies()
   {
      return "human";
   } 

   protected abstract string getName(); 
} 

class FredFlintstone extends Person 
{
   protected string getName()
   {
      return "Fred";
   } 

}

Person person = new FredFlintstone(); 
string hiThere = person.introduction(); 

Not the answer you're looking for? Browse other questions tagged or ask your own question.