<< Hide Menu
3 min read•july 11, 2024
Milo Chang
Milo Chang
🌄 Check out these other AP Computer Science A Resources:
An abstract class is a "root" class that you can derive other classes from. You use them when there are several classes that will have similar methods available. If there is even one abstract method in a class, you must make that class an abstract class!
Abstract classes cannot be instantiated; you can't create an object of an abstract class. You can't do "AbstractClass a = new AbstractClass();". 🚫
In an abstract class, you can have constructors. You can also define methods and variables that the child classes will inherit.
Inside an abstract class, you can have regular methods or abstract methods.
public abstract class Shape
{
protected String name;
public Shape()
{
name = "";
}
public String toString()
{
return name;
}
public abstract double getArea();
}
*** Credit to my AP CS A teacher Mr. Kim for this example ***
For the most part, everything in this abstract class seems to be what would be in a regular class.
You can find the area of different types of shapes (circles, triangles, rectangles, squares, etc.) but they each have different formulas. By using an abstract class, you guarantee that every child of the Shape class (like a Triangle class) will have a method called "getArea". Each child class is free to have its own formula to calculate the area.
public class Circle extends Shape
{
*** The variable "name" is inherited from the parent class, Shape ***
private double r;
public Circle (double x)
{
r = x;
name = "Circle";
}
public double getArea()
{
return MATH.PI*r*r;
// Without this code to implement the method, this class will not
// compile
}
}
*** Credit to my AP CS A teacher Mr. Kim for this example ***
© 2024 Fiveable Inc. All rights reserved.