Vocab Bar | |
---|---|
Abstract Class | A class that represents an abstract concept, and is therefore only partially implemented. |
Abstract Method | A method that has no implementation code, just a header (essentially a placeholder). |
Abstract classes are classes that are not fully implemented because some of their methods represent abstract concepts. For example, if I had a Geometry
class that calculated the area and perimeter of different shapes, the methods would be specific to each different shape (calculating the area of a circle is different than calculating the area of a square). Therefore, the Geometry
class would be an abstract class that had subclasses representing the different shapes (circles, triangles, squares, etc). Below is an example:
public abstract class Geometry {
private String shape;
public Geometry(String shape) {
this.shape = shape;
}
// not all methods in abstract classes must be abstract
public String getShapeName() {
return shape;
}
// abstract methods have no implementation code
public abstract double perimeter();
public abstract double area();
}
/* classes which extend abstract classes must implement all of their abstract methods */
public class Square extends Geometry {
public double sideLength;
public Square(double sideLength, String name) {
super(name);
this.sideLength = sideLength;
}
public double perimeter() {
return 4 * sideLength;
}
public double area() {
return Math.pow(side, 2);
}
}
Abstract classes have a key few rules:
-
If a class has any abstract methods, it must be declared an abstract class (by using the abstract keyword).
-
Any subclass of an abstract class must implement all of the superclass’s abstract methods.
-
Instances of abstract classes cannot be created (because they are incomplete).
-
Constructors are optional in abstract classes.
In order to avoid rule #3, create an object with the type of the abstract class and assign it to an instance of the subclass, as shown below:
Geometry squareProperties = new Square(5, "square");
Overall, abstract classes are very useful when creating classes/methods that cannot be fully defined without more specific information.
Lesson Quiz
1. Which of the following is not a feature of abstract classes?
2. If Car is an abstract class, what must be wrong with the below code?
Car myCar; // variable declaration, line 1
myCar = new Car("Toyota"); // variable assignment, line 2
Written by Chris Elliott
Notice any mistakes? Please email us at learn@teamscode.com so that we can fix any inaccuracies.