CS2514

Introduction to Java

Dr Derek Bridge

School of Computer Science & Information Technology

University College Cork

Abstract classes

Abstract methods

Example of an abstract class

abstract class Animal {
            
    protected String breed;
    
    public Animal(String breed) {
        this.breed = breed;
    }
    
    public String getBreed() {
        return breed;
    }
    
    public abstract void talk();
    
}

An incorrect alternative

Why won't it compile?

Another example

Shapes form a class hierarchy

Another example, cont'd

Shape, an abstract class

class abstract Shape {
       
       protected int x;
       protected int y;
       
       public Shape(int x, int y) {
           this.x = x;
           this.y = y;
       }
       
       public void move(int xChange, int yChange) {
           x = x + xChange;
           y = y + yChange;
       }
       
       public abstract double getArea();
}

One of the subclasses

class Circle extends Shape {

    private int radius;
    
    public Circle(int x, int y, int radius) {
        super(x, y);
        this.radius = radius;
    }
    
    public double getArea() {
        return 3.142 * radius * radius;
    }
              
}

Summary: the usefulness of abstract classes