Amity School of Engineering
[Link]., CSE(5th Sem.) & ECE(3rd Sem.)
Java Programming
Topic: Inheritance
ANIL SAROLIYA
Learning About the Concept of Inheritance
Features of good software design
Correctness Reliability Robustness Reusability Efficiency Ease Of Maintenance
This feature gives the concept of inheritance in Object Oriented Programming
Learning About the Concept of Inheritance
Principle of Inheritance
Applies general knowledge to specific objects Enables one class to derive data and methods of another
Inheritance in non-programming situations
attributes passed on with genes Behaviors may also be passed on with genes
Example drawn from Employee class
Display Employee class in code Use class diagram to specify data and method members Figure: The Employee Class
Learning About the Concept of Inheritance (continued )
Data contained in three rectangles of class diagram
Class name, data Fields, method headers Minus (-) sign before identifier indicates private member Plus (+) sign before identifier indicates public member
Employee class diagram
Private attributes: employee number and salary Public members: (2) getters and (2) setters for data
Figure: The Employee Class Diagram
Every Employee object has some number and salary
4
Learning About the Concept of Inheritance (continued )
EmployeeWithTerritory extends Employee class
EmployeeWithTerritory's relationship to Employee
Inherits public methods of Employee class Adds new private data field for employee territory Adds public setter and getter methods for new data field
Three benefits to extending Employee
Reduced time to code new class (pre-existing tools) Reduced debugging time (building on tested code) Reduced learning time (fewer new methods)
Figure: Relationship between Employee & EmployeeWithTerritory Classes
Learning About the Concept of Inheritance (continued )
Base class: provides basis for inheritance
Also called parent or superclass Example: Employee
Derived class: inherits data and methods from base class
Also called child or subclass Example: EmployeeWithTerritory
Extending Classes
extends keyword achieves inheritance in Java extends used in first line of class declaration
public class EmployeeWithTerritory extends Employee
Employee is superclass to EmployeeWithTerritory subclass
Subclass gets public data and methods from Employee Subclass may have additional data and methods
Inheritance is one-way: child inherits from parent
Figure: The EmployeeWithTerritory Classes
Method Overriding
Overriding Superclass Methods Polymorphism: a feature of object-oriented design
Permits many implementations under one name Sometimes associated with operator overloading (but not in java) Example: Plus (+) sign could mean addition or concatenation
Method overriding is a type of polymorphism
Applies to identical method headers (not overloading) in the multiple classes(under inheritance)
Subtype polymorphism: child overrides parent
10
Understanding How Constructors are Called During Inheritance
As we know that Constructors have same name as class itself Inheritance adds complexity to object construction Superclass and subclass constructors called to create subclass Superclass constructor executes before subclass constructor
public class ASuperClass { public ASuperClass() { [Link]("In superclass constructor"); } } public class ASubClass extends ASuperClass { public ASubClass() { [Link]("In subclass constructor"); } } public class DemoConstructors { public static void main(String[] args) Result: { ASubClass child = new ASubClass(); In superclass constructor } In subclass constructor }
Figure: Three classes that shows constructor calling
when a subclass object is instantiated
11
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
Accessing Superclass Methods
Subclass method overrides parent's with identical signature Overridden parent method may be accessed in subclass Technique: call parent method using super keyword
Example: [Link]( ); appears in child With this compiler binds child class display( ) to parent class
Demonstration: TestCustomers class
Parent class is Customer, child is PreferredCustomer PreferredCustomer's display( ) calls parent's display( )
13
public class Customer { private int idNumber; private double balanceOwed; public Customer(int id, double bal) { idNumber = id; balanceOwed = bal; } public void display() { [Link]("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 { [Link](); [Link]("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); [Link](); Output [Link](); Customer #124 Balance $123.45 } Customer #125 Balance $3456.78 } Discount rate is 0.15
14
Information Hiding
Learning about Information Hiding
Information hiding: concept of keeping data private Information hiding support with three access modifiers private: member known to public member of same class protected: member known within class and child classes public: member generally accessible Data generally declared private or protected Public setters and getters access data Only public or protected members may be inherited111
Figure: The Student Classes
16
Using Methods You Cannot Override
Subclass cannot override three types of method
static methods final methods Methods within final classes
17
A Subclass Cannot Override static Members in Its Superclass
Subclass cannot override static methods in parent Override attempts result in compiler error Example:
public class BaseballPlayer { private int jerseyNumber; private double battingAvg; public static void printOrigins() { [Link]("Abner Doubleday is often " + "credited with inventing baseball"); } } public class ProfessionalBaseballPlayer extends BaseballPlayer { double salary; public void printOrigins() //Trying for overriding, it generates compiler error {
[Link]("The first professional " + "major league baseball game was played in 1871");
} }
Note: Its also not possible for child class to call parent's printOrigins( ) method with super
keyword. Its also leads compilation error.
18
A Subclass Cannot Override static Members in Its Superclass (continued..)
Partial solution: make child's printOrigins( ) method as static Child's static method hides static parent method
public class BaseballPlayer { private int jerseyNumber; private double battingAvg; public static void printOrigins() { [Link]("Abner Doubleday is often " + "credited with inventing baseball"); } } public class ProfessionalBaseballPlayer extends BaseballPlayer { double salary; public static void printOrigins() // hides static parent method & treated as independent method {
[Link]("The first professional " + "major league baseball game was played in 1871");
} }
19
A Subclass Cannot Override static Members in Its Superclass (continued..)
Child may still access parent member Must use parent name in method call
public class BaseballPlayer { private int jerseyNumber; private double battingAvg; public static void printOrigins() { [Link]("Abner Doubleday is often " + "credited with inventing baseball"); } } public class ProfessionalBaseballPlayer extends BaseballPlayer { double salary; public static void printOrigins() { [Link](); //accessing the parent member method
[Link]("The first professional " + "major league baseball game was played in 1871");
} }
20
Output of the previous slide
public class TestProPlayer { public static void main(String[] args) { ProfessionalBaseballPlayer aBowler= new ProfessionalBaseballPlayer(); [Link](); } }
Result:
Abner Doubleday is often credited with inventing baseball The first professional major league baseball game was played in 1871
21
A Subclass Cannot Override final Members in Its Superclass
As we all know, final modifier is used to create constants final modifier may be applied to methods final methods are not overridden by subclass methods What is final Method? Answer: final methods are inlining candidates
Inline: replace method call with method definition final functions bound to objects at compile time virtual functions (default) bound to objects at run time
Example (code available in next slide): Child tries overriding final method in BasketballPlayer class
22
A Subclass Cannot Override final Members in Its Superclass (continued..)
Subclass cannot override final methods in parent Override attempts result in compiler error Example:
public class BasketballPlayer { private int jerseyNumber; public final void printMessage() { [Link] ("Michael Jordan is the " + "greatest basketball player - and that is final"); } } public class ProfessionalBasketballPlayer extends BasketballPlayer { double salary; public final void printMessage() //Trying for overriding, it generates compiler error {
[Link]( I have nothing to say");
} }
23
A Subclass Cannot Override Methods in a final Superclass
Classes may be declared final Internal methods of final classes are automatically converted into final mode Final classes cannot be parents because final access modifier stop sub-classing (inheritance) mechanism Example (code available in next slide): ProfessionalBasketballPlayer tries to override final BasketballPlayer
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() { [Link] ("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 {
[Link]( I have nothing to say");
} }
25
Amity School of Engineering [Link]., CSE(5th Sem.) & ECE(3rd Sem.)
Thanks
26