Lecture 14 Abstract Classes Professor Adams Rules for

Lecture 14 - Abstract Classes Professor Adams

Rules for Abstract Classes § An abstract class can not be instantiated § An abstract class can’t have instances § A class that can have instances is said to be concrete § An abstract class provides a prototype for other classes to follow

Subclasses of an Abstract Class § will inherit the variables and methods of the abstract class § will have the same basic characteristics § are free to redefine variables and methods and add new ones § must override any abstract methods of its parent.

Abstract Classes § generally contain at least one abstract method § are not required by the compiler to be declared abstract – but we require it § are any classes containing at least one abstract method § can contain non-abstract methods

Abstract Methods § § have the word abstract in their declaration do not have a body end their declarations with a semi-colon must be overriden in children of containing class § are generally methods whose bodies will change from one subclass to another

Standard UML Notation § § § + public - private # protected {abstract} top compartment – class name middle compartment – class attributes l name : type § bottom compartment – class methods l return. Type name (parameter. List types)

Abstract Classes Some Lewis & Loftus slides

Abstract Classes § An abstract class is a placeholder in a class hierarchy that represents a generic concept § An abstract class cannot be instantiated § We use the modifier abstract on the class header to declare a class as abstract: public abstract class Whatever { // contents }

Abstract Classes § An abstract class often contains abstract methods with no definitions § the abstract modifier must be applied to each abstract method § An abstract class typically contains non-abstract methods (with bodies) § A class declared as abstract does not need to contain abstract methods

Abstract Classes § The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract § An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet) § The use of abstract classes is a design decision – it helps us establish common elements in a class that is too general to instantiate

Indirect Use of Members Inheritance § An inherited member can be referenced directly by name in the child class, as if it were declared in the child class § But even if a method or variable is not inherited by a child, it can still be accessed indirectly through parent methods § See Food. Analyzer. java (page 459) § See Food. Item. java(page 460) § See Pizza. java (page 461)
- Slides: 11