Professional Documents
Culture Documents
Abstract Classes
3 / 41
Abstract classes
From the previous lecture:
// Constructors…
// get/set methods…
}
4 / 41
Abstract classes
So we can do:
Abstract classes
So we can do:
Abstract classes
Solution:
Make it abstract!
7 / 41
Abstract classes
Solution:
Make it abstract!
Abstract classes
Used for defining classes for “abstract” concepts.
(‘GeometricObject’, ‘Animal’, etc.)
9 / 41
Abstract classes
Used for defining classes for “abstract” concepts.
(‘GeometricObject’, ‘Animal’, etc.)
Abstract classes
Used for defining classes for “abstract” concepts.
(‘GeometricObject’, ‘Animal’, etc.)
Abstract classes
Every GeometricObject has an area.
12 / 41
Abstract classes
Every GeometricObject has an area.
Abstract classes
Every GeometricObject has an area.
Abstract classes
// Circle
public class Circle extends GeometricObject {
public float getArea() {
return Math.PI * radius * radius;
}
}
15 / 41
Abstract classes
// Circle
public class Circle extends GeometricObject {
public float getArea() {
return Math.PI * radius * radius;
}
}
// Rectangle
public class Rectangle extends GeometricObject {
Abstract classes
GeometricObject[] objs = new GeometricObject[2];
objs[0] = new Circle(3);
objs[1] = new Rectangle(1, 2);
Abstract classes
GeometricObject[] objs = new GeometricObject[2];
objs[0] = new Circle(3);
objs[1] = new Rectangle(1, 2);
Abstract classes
So make getArea() an abstract method in
GeometricObject.
19 / 41
Abstract classes
So make getArea() an abstract method in
GeometricObject.
Abstract classes
GeometricObject[] objs = new GeometricObject[2];
objs[0] = new Circle(3);
objs[1] = new Rectangle(1, 2);
Example:
GeometricObject gObj;
Abstract classes
Let’s say we need to check if areas of
GeometricObjects are equal
29 / 41
Abstract classes
Let’s say we need to check if areas of
GeometricObjects are equal
Abstract classes
public static void main(String[] args) {
Circle c1 = new Circle(3.0);
Rectangle r1 = new Rectangle(2, 3);
Rectangle r2 = new Rectangle(1, 6);
Abstract classes
How do you define equalArea(...)?
32 / 41
Abstract classes
How do you define equalArea(...)?
Abstract classes
Could define it for all different comparisons:
Abstract classes
Could define it for all different comparisons:
Abstract classes
Could define it for all different comparisons:
Abstract classes
Could define it for all different comparisons:
Tedious...
37 / 41
Abstract classes
Make it general thanks to abstract methods/classes:
Abstract classes
Why not use the Object class?
Abstract classes
Why not use the Object class?
Abstract classes
Why not use the Object class?
Abstract classes
Why not use the Object class?
Next Lecture...
Interfaces.