Interfaces
Interfaces
Inherit a class
How to inherit a class and implement an interface
- A class can inherit another class and also implement one or more interfaces.
- If a class inherits another class that implements an interface:
- the subclass automatically implements the interface (but you can code the implements keyword in the subclass for clarity)
- the subclass has access to any methods of the interface that are implemented by the superclass and can override those methods
The syntax for inheriting a class and implementing an interface
public class SubclassName extends SuperclassName implements Interface1[, Interface2]...{}
A Book class that inherits Product and implements Printable
public class Book extends Product implements Printable { private String author; public Book(String code, String description, double price, String author) { super(code, description, price); this.author = author; } public void setAuthor(String author) { this.author = author; } public String getAuthor() { return author; } public void print() // implement the Printable // interface { System.out.println("Code:\t" + super.getCode()); System.out.println("Title:\t" + super.getDescription()); System.out.println("Author:\t" + this.author); System.out.println("Price:\t" + super.getFormattedPrice()); } }