Abstract Classes

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Abstract Classes

Used for: representing parent classes that exist only for being a parent class.

Syntax: abstract (class keyword)

public abstract class MyClass {...}

We cannot make instances of this class (cannot use “new” keyword)

Abstract Methods

Method that exist only to provide structure

Syntax: list modifier abstract with the method

public abstract int getSomething();
  • Only allowed on abstract classes
  • Method does not have a body (end line with semi-colon)
  • Child class inherits obligation to implement
  • Java knows method exists (you can call it)

Practice – Greeter Class

The greeter classes represent various ways to greet someone

  • public: getName, greet
  • private: name – should be handled well (set in constructor)

Things to note:

  • Parent class provides structure to child classes
  • in-class polymorphic methods

Practice – main function

Submit your Greeter.java, Informal.java and Formal.java to gradescope

You can use this Greet.java main to test your code in your computer:

public class Greet {

    public static void main(String[] args) {
        Greeter boss = new Formal("Ms.", "Silva");
        boss.greet();

        Greeter friend = new Informal("Joe");
        friend.greet();

    }
}
Good day, Ms. Silva.
What's up, Joe?

Solution Greeter.java

public abstract class Greeter {
    private String name;

    public Greeter(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public abstract void greet();

}

Solution Formal.java

public class Formal extends Greeter {
    private String title;

    public Formal(String title, String name) {
        super(name);
        this.title = title;
    }

    @Override
    public String getName() {
        return this.title + " " + super.getName();
    }

    public void greet() {
        System.out.println("Good day, " + getName() + ".");
    }
}

Solution Informal.java

public class Informal extends Greeter {

    public Informal(String name) {
        super(name);
    }

    public void greet() {
        System.out.println("What's up, " + super.getName() + "?");
    }
}