Upload
mallika-raghuvanshi
View
24
Download
2
Tags:
Embed Size (px)
Citation preview
1
Amity School of EngineeringB.Tech., CSE(5th Sem.) & ECE(3rd Sem.)
Java ProgrammingTopic: Inheritance
ANIL SAROLIYA
2
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
3
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
4
Learning About the Concept of Inheritance (continued…)
Figure: The Employee Class Diagram
• 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 • Every Employee object has some
number and salary
5
Learning About the Concept of Inheritance (continued…)
• 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)
EmployeeWithTerritory extends Employee class
Figure: Relationship between Employee & EmployeeWithTerritory Classes
6
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
7
• 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
Extending Classes
Figure: The EmployeeWithTerritory Classes
Method Overriding
10
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
public class ASuperClass{ public ASuperClass() { System.out.println("In superclass constructor"); }}public class ASubClass extends ASuperClass{ public ASubClass() { System.out.println("In subclass constructor"); }}public class DemoConstructors{ public static void main(String[] args) { ASubClass child = new ASubClass(); }}
11
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
Figure: Three classes that shows constructor calling when a subclass object is instantiated
Result:In superclass constructorIn subclass constructor
12
• 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
Using Superclass Constructors that Require Arguments
13
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: super.display( ); 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( )
14
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(); onePCust.display(); }}
OutputCustomer #124 Balance $123.45Customer #125 Balance $3456.78Discount rate is 0.15
Information Hiding
16
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
17
Using Methods You Cannot Override
• Subclass cannot override three types of method – static methods– final methods– Methods within final classes
18
A Subclass Cannot Override static Members in Its Superclass• Subclass cannot override static methods in parent• Override attempts result in compiler errorExample:
public class BaseballPlayer{ private int jerseyNumber; private double battingAvg; public static void printOrigins() { System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); }}public class ProfessionalBaseballPlayer extends BaseballPlayer{ double salary; public void printOrigins() { System.out.println("The first professional " + "major league baseball game was played in 1871"); }}
//Trying for overriding, it generates compiler error
Note: Its also not possible for child class to call parent's printOrigins( ) method with super keyword. Its also leads compilation error.
19
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() { System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); }}public class ProfessionalBaseballPlayer extends BaseballPlayer{ double salary; public static void printOrigins() { System.out.println("The first professional " + "major league baseball game was played in 1871"); }}
// hides static parent method & treated as independent method
20
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() { System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); }}public class ProfessionalBaseballPlayer extends BaseballPlayer{ double salary; public static void printOrigins() { System.out.println("The first professional " + "major league baseball game was played in 1871"); }}
BaseballPlayer.printOrigins(); //accessing the parent member method
21
Output of the previous slide
public class TestProPlayer{ public static void main(String[] args) { ProfessionalBaseballPlayer aBowler= new ProfessionalBaseballPlayer(); aBowler.printOrigins(); }}
Result:Abner Doubleday is often credited with inventing baseballThe first professional major league baseball game was played in 1871
22
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 methodsWhat 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
23
• Subclass cannot override final methods in parent• Override attempts result in compiler errorExample:
public class BasketballPlayer{ private int jerseyNumber; public final void printMessage() { System.out.println ("Michael Jordan is the " + "greatest basketball player - and that is final"); }}public class ProfessionalBasketballPlayer extends BasketballPlayer{ double salary; public final void printMessage() { System.out.println(“I have nothing to say"); }}
//Trying for overriding, it generates compiler error
A Subclass Cannot Override final Members in Its Superclass (continued..)
24
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) mechanismExample (code available in next slide):
ProfessionalBasketballPlayer tries to override final BasketballPlayer
25
• Following override attempts result in compiler errorExample: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"); }}
public class ProfessionalBasketballPlayer extends BasketballPlayer{ double salary; public final void printMessage() { System.out.println(“I have nothing to say"); }}
//Trying for overriding generates compiler error
A Subclass Cannot Override Methods in a final Superclass (continued..)
Not possible to inherit the final class
Thanks
26
Amity School of EngineeringB.Tech., CSE(5th Sem.) & ECE(3rd Sem.)