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 aDogandDuckclasses. Below is a UML diagram of these three clases
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
- an abstract class cannot be directly instantiated in a client class.
- ie Animal myAnimal = new Animal(); will not compile. Since Animal is abstract, it cannot be instantiated.
- an abstract class can (but is not required to) have abstract methods
. To make a method an abstract method just add the word 'abstract' in the method header. An abstract method has no code! The idea is that the subclasses will fill in the details by overriding the abstract method
- Example of how to declare an abstract method:
public abstract void makeNoise();
Animal'smakeNoise()method..
- Example of how to declare an abstract method:
What is an Abstract Class in Java?
How Sublcasses use an Abstract Superclass
We are going to talk about two classes that extend AnimalA 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
public class Dog extends Animal{ ..} public class Duck extends Animal{ ..}
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 firtst). Below is my creative implementation of the makeNoise() method in the Dog and Duck methods
-
public class Dog extends Animal{ public void makeNoise(){ System.out.println("roof roof!"); } } -
public class Duck extends Animal{ public void makeNoise(){ System.out.println("quack quack!"); } }
Source Code: Animal class | Dog | Duck | AnimalFarmTester