Abstract Classes
Objective #1: Use abstract classes and abstract methods
- An abstract class is one that uses the abstract keyword in its header as in
public abstract class Solid
- Zero or more methods can be made abstract in an abstract class. An abstract method is a method that does not have an implementation.
- If a class fully implements all of its methods and does not use the abstract keyword, then it is called a concrete class. Classes that we wrote and studied for the first half of the school year were considered to be concrete classes.
- Subclasses that are extended from an abstract parent class may fully implement one or more of the abstract methods. If a subclass of an abstract class does not implement all of the abstract methods then it is also considered to be an abstract class.
- Sometimes no methods of an abstract class are defined as abstract! This is done simply to prevent a client programmer from constructing (i.e. instantiating) objects of the abstract class.
- Unlike an interface, an abstract class can include instance fields and it can include some fully implemented methods.
- Methods in an abstract class can be private. Note that this is another difference between abstract classes and interfaces, which can only have public methods.
- It is not possible to construct (i.e. instantiate) an object from an abstract class just like it is not possible to instantiate an object from an interface. The following statement would cause an error.
MyAbstractClass example = new MyAbstractClass();
But it is possible to simply declare a reference to an abstract class.
MyAbstractClass example;
It is also possible to set a reference of an abstract class equal to null as in
MyAbstractClass example = null;
- If Solid is an abstract class and if Sphere is a concrete subclass of Solid the following is legal
Solid example = new Sphere();
or
Solid example;
example = new Sphere();
- A class can implement an interface and only implement some of the methods from the interface. In this case, the class must be declared as abstract. The class doesn't need to include method signatures for the abstract methods that were not implemented.
- Here is a complete example of an abstract class named ModelStudent, a concrete class named Sophomore, and a client program:
public abstract class ModelStudent
{
private double gpa;
public abstract void doHomework();
public void attendClass()
{
System.out.println("Hi, I'm here in class");
}
}
public class Sophomore extends ModelStudent
{
public void doHomework()
{
System.out.println("Sophomores do their homework immediately when they get home");
}
}
public class AbstractClassDemo
{
public static void main(String[] args)
{
ModelStudent alex = null;
ModelStudent dan = new Sophomore();
ModelStudent matt = new ModelStudent(); // illegal
dan.doHomework();
}
}
- Here is a discussion on the differences between interfaces & abstract classes and when to use each
http://mindprod.com/jgloss/interfacevsabstract.html