Abstract Classes and Polymorphism
Abstract classes are classes that contain at least one
abstract method. An abstract
method is a method with no statements. It also has keyword abstract on its
declaration. No brackets. Classes of this type also have the keyword abstract
in their declaration.
If you create a subclass of an abstract class, you must
provide the actions
or implementation of the inherited abstract methods. You can still inherit
the other methods implemented in the abstract class, write your own methods,
override methods, or overload methods but you must provide the code to
implement the abstract method that was declared in the super class.
This sets up the following important concept
--polymorphism. because the
abstract method declared in the syperclass mist be implemented in each
subclass. The same method name must be used. Hence different subclasses
of the same superclass can each define different actions (implementations)
of the same method name. The superclass provides a framework for
conformity but the concept of polymorphism allows for flexibility in
in creation of subclass objects.
The example below demonstrates polymorphism as it applies
to a superclass
and 2 subclasses.
****************************************************
public abstract class Animal //
superclass
{
private String name;
public amimal(String ss)
{
name=ss;
}
public String getName()
{
return name;
}
public abstract void speak();
}
"""""""""""""""""""""""""""""""""""""""""""""""
public class Dog extends Animal
{
public Dog(String aa)
{
super(aa);
}
public void speak()
{
System.out.Println("roof");
}
}
*****************************************************
public class Cow extends Animal
{
public Cow(String aa)
{
super(aa);
}
public void speak()
{
System.out.Println("moo");
}
}
*****************************************************
public class Cat extends Animal
{
public Cat(String aa)
{
super(aa);
}
public void speak()
{
System.out.Println("meow");
}
}
NOTE... Obviously some other class will create the Dog, Cat and Cow objects
ALSO note the "super" command. When an object of a subclass is created
the constructor of the superclass is automatically called first implicitly.
If you want to pass parameters to the superclass then use the "super"
command as noted above.