Show Core ConceptsInheritance has the same core concepts in any object-oriented language
Inheritance in JavaUse the keyword extends to declare the derived class// Example 1 public class AAA // AAA is the base class { ... } public class BBB extends AAA // BBB is the derived class { ... } // Example 2 public class Employee {...} // base class public class HourlyEmployee extends Employee { ... } // derived keyword superYou can use super like a function call in a derived class constructor -- invokes the base class constructorsuper(); // invokes base class default constructor super(parameters); // invokes base class constructor with parameters // Example, for a class called HourlyEmployee, derived from Employee public class HourlyEmployee extends Employee { public HourlyEmployee() // default constructor { super(); // invokes Employee() constructor } public HourlyEmployee(double h, double r) { super(h,r); // invokes Employee constructor w/ 2 parameters } // ... more methods and data } // end class HourlyEmployee
The protected modifier
The final modifierUse in Java for a few special inheritence-related purposes:
Other differences
Method OverridingJust like in C++, this is when a derived class has a method with the same prototype as a method in the base class. (The derived class function overrides the base class version, when called for a derived object).Example:
Abstract Classes
Which keyword can be used to call the constructor of a parent class?3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor.
Can a subclass call the parent's class constructor and when?The parent constructor must be called by the subclass's constructor, however this does not always require an explicit super() call. If the parent class has a default (no-argument) constructor, then it will automatically be called by the subclass constructor if you omit the call to super() .
|