11 Inheritance
11 Inheritance
Java Programming
Topic: Inheritance
ANIL SAROLIYA
Extending Classes
extends keyword achieves inheritance in Java extends used in first line of class declaration
public class EmployeeWithTerritory extends Employee
Method Overriding
Using Superclass Constructors that Require Arguments Default constructor never requires arguments
Java automatically provides default constructor Programmers may define default constructor
Subclass may use superclass default constructor Some superclasses only have parameterized constructors If Superclass lacks default, subclass calls superclass constructor
Format of statement: create super (list of arguments) in subclass constructor Call to superclass constructor executed first
12
Subclass method overrides parent's with identical signature Overridden parent method may be accessed in subclass Technique: call parent method using super keyword
Example: super.display( ); appears in child With this compiler binds child class display( ) to parent class
13
public class Customer { private int idNumber; private double balanceOwed; public Customer(int id, double bal) { idNumber = id; balanceOwed = bal; } public void display() { System.out.println("Customer #" + idNumber + " Balance $" + balanceOwed); } } public class PreferredCustomer extends Customer { double discountRate; public PreferredCustomer(int id, double bal, double rate) //in child class { super (id, bal); discountRate = rate; } public void display() //in child class { super.display(); System.out.println("Discount rate is " + discountRate); } } public class TestCustomers { public static void main(String[] args) { Customer oneCust = new Customer(124, 123.45); PreferredCustomer onePCust = new PreferredCustomer(125, 3456.78, 0.15); oneCust.display(); Output onePCust.display(); Customer #124 Balance $123.45 } Customer #125 Balance $3456.78 } Discount rate is 0.15
14
Information Hiding
16
17
} }
Note: Its also not possible for child class to call parent's printOrigins( ) method with super
keyword. Its also leads compilation error.
18
} }
19
} }
20
Result:
Abner Doubleday is often credited with inventing baseball The first professional major league baseball game was played in 1871
21
Example (code available in next slide): Child tries overriding final method in BasketballPlayer class
22
} }
23
24
A Subclass Cannot Override Methods in a final Superclass (continued..) Following override attempts result in compiler error Example:
public final class BasketballPlayer { private int jerseyNumber; public final void printMessage() { System.out.println ("Michael Jordan is the " + "greatest basketball player - and that is final"); } } Not possible to inherit the final class public class ProfessionalBasketballPlayer extends BasketballPlayer { double salary; public final void printMessage() //Trying for overriding generates compiler error {
System.out.println( I have nothing to say");
} }
25
Thanks
26