CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Inheritance

Inheritance
Abstract and final keywords
abstract keyword

How to work with the abstract keyword

  • An abstract class is a class that can be inherited by other classes but that you can't use to create an object.
  • To declare an abstract class, code the abstract keyword in the class declaration.
  • An abstract class can contain fields, constructors, and methods just like other superclasses. It can also contain abstract methods.

  • To create an abstract method, you code the abstract keyword in the method declaration and you omit the method body.
  • Abstract methods cannot have private access. However, they may have protected or default access (no access modifier).
  • When a subclass inherits an abstract class, all abstract methods in the abstract class must be overridden in the subclass.
  • Any class that contains an abstract method must be declared as abstract.

An abstract Product class

public abstract class Product
{
    private String code;
    private String description;
    private double price;

    // regular constructors and methods for instance
    // variables

    public String toString()
    {
        return "Code:        " + code + "\n" +
               "Description: " + description + "\n" +
               "Price:       "
               + this.getFormattedPrice() + "\n";
    }

    abstract String getDisplayText();  // an abstract method
}

A class that inherits the abstract Product class

public class Book extends Product
{
    private String author;

    // regular constructor and methods for the Book class

    public String getDisplayText()
                         // implement the abstract method
    {
        return super.toString() +
            "Author:      " + author + "\n";
    }
}
Previous | abstract keyword | final keyword