-
The classes that lie closer to the top of the hierarchy are more general and abstract; the classes closer to the bottom are more specialized. Java allows us to formally define an abstract class. In an abstract class, some or all methods are declared abstract
and left without code.
-
An abstract
method has only a heading: a declaration that gives the method’s name, return type, and arguments. An abstract
method has no code. For example, all of the methods in the definition of the SeaCreature
class shown below are abstract. SeaCreature
tells us what methods a sea creature must have, but not how they work.
// A type of creature in the sea
public abstract class SeaCreature{
// Called to move the creature in its environment
public abstract void swim();
// Attempts to breed into neighboring locations
public abstract void breed();
// Removes this creature from the environment
public abstract void die();
// Returns the name of the creature
public abstract String getName();
}
-
In an abstract
class, some methods and constructors may be fully defined and have code supplied for them while other methods are abstract
. A class may be declared abstract
for other reasons as well. For example, some of the instance variables in an abstract
class may belong to abstract
classes.
-
More specialized subclasses of an abstract
class have more and more methods defined. Eventually, down the inheritance line, the code is supplied for all methods. A class where all the methods are fully defined is called a concrete class. A program can only create objects of concrete classes. An object is called an instance of its class. An abstract
class cannot be instantiated.
-
Different concrete classes in the same hierarchy may define the same method in different ways. For example:
public class Fish extends SeaCreature{
...
/**
* Returns the name of the creature
*/
public String getName(){
return "Wanda the Fish";
}
...
}
public class Mermaid extends SeaCreature{
...
/**
* Returns the name of the creature
*/
public String getName(){
return "Ariel the Mermaid";
}
...
}