Abstract Classes and Inheritance

[ Home] [ Site Map ]

Links:

On this page I will be referring to the following abstract class
public abstract class Animal{
//code will be filled in later on ...
}
I will also be referring to a Dog and Duck classes. Below is a UML diagram of these three classes
Source Code: Animal class | Dog | Duck | AnimalFarmTester


In Java, an abstract class is a special type of class. First off, an abstract class must be a superclass and an abstract class cannot be directly instantiated.. Since you cannot instantiate abstract classes, the sole point of an this type of class is to organize code that will be common to subclasses. Well that sounds like a regular old superclass right? First, let's try to understand how to create an abstract class and what it is, then further down the page we'll discuss when it is appropriate to declare a class as abstract.. Here are the main traits of abstract classes

How Subclasses use an Abstract Superclass

We are going to talk about two classes that extend Animal
public class Dog extends Animal{ ..}
public class Duck extends Animal{ ..}
A class that extends Animal must...I repeat --must--implement any methods that were declared as abstract. In our case,the only abstract method that Animal has is makeNoise(); Therefore, both Dog and Duck must actually implement these methods. (The only time you can avoid this is if the subclass is also abstract--a technicality you might not want to worry about at first). Below is my creative implementation of the makeNoise() method in the Dog and Duck methods
Source Code: Animal class | Dog | Duck | AnimalFarmTester
When should you declare a superclass abstract?
A tellign sign that a superclass should be declared abstract is if you know that all subclasses will need to overrride a given method. For instance, since both Dog and Duck completely override makeNoise(), it made sense to declare that method abstract.
Site Map | Resources | Online Math Games | Fraction Games Online | TOS | Programming Homework Help Sitemap