1 of 12

Abstract Classes

AP Computer Science A

Chris Vollmer

2 of 12

Purpose of Abstract Classes

  • An abstract class is a placeholder in a class hierarchy that represents a generic concept

  • An abstract class is a class that is declared abstract
    • it may or may not include abstract methods.

  • Cannot be instantiated, but they can be subclassed.

3 of 12

Abstract Classes

  • We use the modifier abstract on the class header to declare a class as abstract:

public abstract class Whatever

{

// contents

}

4 of 12

Abstract Classes

  • Subclass usually provides implementations for all of the abstract methods in its parent class.
    • if it does not, then the subclass must also be declared abstract.

5 of 12

Abstract Class - Code

public abstract class MyAbstractClass

{� public abstract void abstractMethod( );�}

public class MySubClass extends MyAbstractClass

{� public void abstractMethod( )

{� System.out.println("My method implementation");� }�}

6 of 12

Abstract Classes

  • An abstract class often contains abstract methods with no definitions (like an interface does)
  • Unlike an interface, the abstract modifier must be applied to each abstract method
  • Typically contains non-abstract methods (with bodies), further distinguishing abstract classes from interfaces
  • A class declared as abstract does not need to contain abstract methods

7 of 12

  • You want to share code among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields.
    • This enables you to define methods that can access and modify the state of the object to which they belong.

When to Use?

8 of 12

9 of 12

Abstract Classes

  • The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract
  • An abstract method cannot be defined as static (because it has no definition yet)
  • The use of abstract classes is a design decision – it helps us establish common elements in a class that is too general to instantiate

10 of 12

abstract class GraphicObject

{� int x, y;� ...

void moveTo(int newX, int newY)

{� ...� }� abstract void draw();� abstract void resize();�}

class Rectangle extends GraphicObject

{� void draw() { definition }� void resize() { definition }

}

class Circle extends GraphicObject {� void draw() { definition }� void resize() { definition }�}

11 of 12

Resources

  • See Pets.java (page 411)
  • See Pet.java (page 412)
  • See Dog.java (page 413)
  • See Snake.java (page 414)

https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

12 of 12