Java Inheritance
Inheritance is the process by which a new class is created from another class
- The new class is called a derived class, or child class
- The original class is called the base class (super class) or parent class
A derived class automatically has all the instance variables and methods that the base class has, and it can have additional methods and/or instance variables as well
keyword: extends
public clase HourlyEmployee extends Employee{ private double wageRate; private double hour; public HourlyEmployee(){ super(); wageRate = 0; hour = 0; } }
super(): A derived class uses a constructor from the base class to initialize all the data inherited from the base class
- A call to the base class constructor can never use the name of the base class, but uses the keyword super instead
- A call to super must always be the first action taken in a constructor definition
Although a derived class inherits methods from the base class, it can change or override an inherited method if necessary
final keyword:
- If the modifier final is placed before the definition of a method, then that method may not be redefined in a derived class
- If the modifier final is placed before the definition of a class, then that class may not be used as a base class to derive other classes
Overiding vs Overloading
- Overiding: 修改base class中某個method的內容,但parameter數量不變
- Overloading: 某method支援多種數量的parameter
implements keyword: Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class.
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface.