Inheritance
Basic skills
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 subclasspublic class SubclassName extends SuperClassName{}To call a superclass constructorsuper(argumentList)To call a superclass methodsuper.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; } }