26
1 Amity School of Engineering B.Tech., CSE(5 th Sem.) & ECE(3 rd Sem.) Java Programming Topic: Inheritance ANIL SAROLIYA

11 Inheritance

Embed Size (px)

Citation preview

Page 1: 11 Inheritance

1

Amity School of EngineeringB.Tech., CSE(5th Sem.) & ECE(3rd Sem.)

Java ProgrammingTopic: Inheritance

ANIL SAROLIYA

Page 2: 11 Inheritance

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

Page 3: 11 Inheritance

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

Page 4: 11 Inheritance

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

Page 5: 11 Inheritance

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

Page 6: 11 Inheritance

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

Page 7: 11 Inheritance

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

Page 8: 11 Inheritance

Figure: The EmployeeWithTerritory Classes

Page 9: 11 Inheritance

Method Overriding

Page 10: 11 Inheritance

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

Page 11: 11 Inheritance

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

Page 12: 11 Inheritance

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

Page 13: 11 Inheritance

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( )

Page 14: 11 Inheritance

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

Page 15: 11 Inheritance

Information Hiding

Page 16: 11 Inheritance

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

Page 17: 11 Inheritance

17

Using Methods You Cannot Override

• Subclass cannot override three types of method – static methods– final methods– Methods within final classes

Page 18: 11 Inheritance

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.

Page 19: 11 Inheritance

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

Page 20: 11 Inheritance

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

Page 21: 11 Inheritance

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

Page 22: 11 Inheritance

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

Page 23: 11 Inheritance

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..)

Page 24: 11 Inheritance

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

Page 25: 11 Inheritance

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

Page 26: 11 Inheritance

Thanks

26

Amity School of EngineeringB.Tech., CSE(5th Sem.) & ECE(3rd Sem.)