Tuesday, 15 December 2009

Abstract classes

As seen from the previous example, the superclass is more general than its subclass(es). The superclass contains elements and properties common to all of the subclasses. The previous example was of a concrete superclass that instance objects can be created from. Often, the superclass will be set up as an abstract class which does not allow objects of its prototype to be created. In this case, only objects of the subclass are used. To do this the reserved word abstract is included in the class definition.
Abstract methods are methods with no body specification. Subclasses must provide the method statements for their particular meaning. If the method was one provided by the superclass, it would require overriding in each subclass. And if one forgot to override, the applied method statements may be inappropriate.

public abstract class Animal  // class is abstract
{
  private String name;
  public Animal(String nm)      // constructor method
  { name=nm; }
  public String getName()       // regular method
  { return (name); }
  public abstract void speak(); // abstract method - note no {}
}


Abstract classes and methods force prototype standards to be followed (ie. they provide templates).
See also - Abstract classes : cpp vs java

No comments:

Post a Comment