CIS 35A: Introduction to Java Programming

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

Inheritance

Inheritance
Basic skills
Subclass

How to create a subclass

  • You can directly access fields that have public or protected access in the superclass.
  • You can extend the superclass by adding new fields/properties, constructors, and methods.
  • You can override methods in the superclass by coding methods that have the same signatures.
  • You use the super keyword to call a constructor or method of the superclass. If necessary, you can call constructors or methods that pass arguments to the superclass.

The syntax for creating subclasses

To declare a subclass
public class SubclassName extends SuperClassName{}
To call a superclass constructor
super(argumentList)
To call a superclass method
super.methodName(argumentList)

Superclass's Constructor Is Always Invoked

A constructor may invoke an overloaded constructor or its superclass's constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor.

Java requires that the statement that uses the keyword super appear first in the constructor.

The code for a Book subclass

public class Book extends Product
{
    private String author;

    public Book()
    {
        super();  // call constructor of Product superclass
        author = "";
        count++;  // update the count variable in the Product superclass
    }

    public void setAuthor(String author)
    {
        this.author = author;
    }

    public String getAuthor()
    {
        return author;
    }

    public String toString()    // override the toString method
    {
        String message = super.toString() +  // call method of Product superclass
            "Author:      " + author + "\n";
        return message;
    }
}
Previous | Superclass | Subclass | Overriding methods in the Superclass | Polymorphism | Next