Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance What is inheritance? Why is it used in Java?

Similar presentations


Presentation on theme: "Inheritance What is inheritance? Why is it used in Java?"— Presentation transcript:

1

2 Inheritance What is inheritance? Why is it used in Java?

3 Terminology Parent: Super Child: Sub Example class Car extends Vehicle Car is a child or subclass of Vehicle and Vehicle is a parent or superclass of Car.

4 Process What actually happens in a coding context?

5 Bank Employee Example Types of Employee Basic type – gardener, cleaner Teller Manager What do they have in common? A Teller is also an employee A Manager is also a Teller (and therefore an Employee) So we can save effort by reusing relevant classes

6 Inheritance diagram Teller Employee Manager

7 Object of Type Teller contains Teller Object Employee Object

8 Object of Type Manager contains Teller Object Employee Object Manager Object

9 Basic Employee class Employee { private String name; private int hourlyWage; public void setupObject(String nameParameter, int hourlyWageParameter) { name = nameParameter; hourlyWage = hourlyWageParameter; } // End setupObject public String getName() { return name; } // End getName public int calculateWages(int hoursWorked) { return (hoursWorked * hourlyWage); } // End calculateWages // Other methods such as changeWages, etc would go here } // End Employee

10 Object of type Teller contains Object of type Teller Variables Methods Object of type Employee Variables Methods

11 Teller class Teller ……… { private int …….. public void lodgeMoney(int amountToLodge) { totalLodged += amountToLodge; } // End lodgeMoney public void withDrawMoney(int amountToWithdraw) { totalWithdrawn += amountToWithdraw; } // End withDrawMoney // Other methods such as getTotalLodged, etc would go here } // End Teller

12 Object of type Manager contains Object of type Manager Variables Methods Object of type Teller Variables Methods Object of type Employee Variables Methods

13 Manager class Manager………… { private int …………. public void approveLoan(int loanAmount) { loansApproved += loanAmount; } // End approveLoan // Other methods such as getLoans etc would go here } // End Manager

14 Why is inheritance so important? It allows code to be reused/altered without affecting the original code Problem solutions can be divided into easy to handle sections which are straightforward to assemble (a Lego analogy is often used) Added layers of complexity and functionality can be assembled while compartmentalising the sections.


Download ppt "Inheritance What is inheritance? Why is it used in Java?"

Similar presentations


Ads by Google