Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Goals  To learn about inheritance  To implement subclasses that inherit and override superclass methods  To understand the concept of polymorphism  To be familiar with the common superclass Object and its methods

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Inheritance Hierarchies  Inheritance: the relationship between a more general class (superclass) and a more specialized class (subclass). IS-A relationship Figure 1 An Inheritance Hierarchy of Vehicle Classes Vehicle Motorcycle Car Truck Sedan SUV

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 QUESTION  Inheritance = IS-A relation  Which ones have inheritance relation? Which ones are the super class and subclass? 1.Person, Student 2.Car,Person 3.Car,Vehicle

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 ANSWER  Inheritance = IS-A relation  Which ones have inheritance relation? Person is a Student Student is a Person Student = Subclass Person = super class Car is a Person Car is a Vehicle Car= Subclass Vehicle= super class Superclass Subclass

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Inheritance Hierarchies  Inheritance lets you can reuse code instead of duplicating it.  A class can be defined as a "subclass" of another class. The subclass inherits Non-private data attributes of its superclass The subclass inherits Non-private methods of its superclass The subclass can: Add new functionality Use inherited functionality Override inherited functionality (modify) Employee -name -Id +getId() +getName() +calculateSalary() +setName(name) +setId(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Employee -name -Id +claculateSalary() +getName() +setID(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate() parent/supercalss of SalariedEmployee class and CommissionEmployee Additional attributes Additional methods Inherited + overridden by subclasses Inherited and used as it is by subclasses

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 What does a subclass inherit?  A subclass inherits : Non-private Superclass variables Non-private Superclass methods  A subclass does NOT inherit: Superclass constructors Superclass private variables Superclass private methods.  Inherited variables and methods behave as though they were declared in the subclass.  The subclass may define additional variables and methods that were not present in the superclass.

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Inheritance in java  In Java, inheritanc is accomplished by extending an existing class (using keyword extends ).  A superclass can be any previously existing class, including a class in the Java API.  E.g.: public class SalariedEmployee extends Employee { … } Subclass of Employee Superclass of salariedEmployee

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Writing a Subclass Example Public class Employee { private String name; private int id; public double calculateSalary(){return 2000.0;} public int getId() { return id; } public String getName(){ return name;} public void setId(int id){ this.id = id;} public void setName(String name) { this.name = name; } } Public class SalariedEmployee extends Employee { private double weeklySalary; public double calculateSalary(){return this.weeklySalary*4;} public double calculateBonus(){return this.weeklySalary*0.5; } } Employee.java SalariedEmployee.java Subclass: Superclass:

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Question  Which of the following code lines gives compilation errors? Public class SalariedEmployee extends Employee { private double weeklySalary; public double calculateBonus(){ System.out.println(“calculationg bonus of employee with name:”+getName()+” id:”+id); return this.weeklySalary*0.5; }

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Answer  Print statement will result in compiler error as it is private in Employee class. Public class SalariedEmployee extends Employee { private double weeklySalary; public double calculateBonus(){ System.out.println(“calculationg bonus of employee with name:”+getName()+” id:”+id); return this.weeklySalary*0.5; }

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14  Corrected version public class SalariedEmployee extends Employee { private double weeklySalary; public double calculateSalary() { return this.weeklySalary*4; } public double calculateBonus() { System.out.println("calculationg bonus of employee with name:"+getName()+" id:"+getId()); return this.weeklySalary*0.5; }

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Question  Which of these statements will result in compiler error? public class EmployeeDemo { public static void main(String args[]) { SalariedEmployee salEmp = new SalariedEmployee(); salEmp.calculateBonus(); salEmp.setId(12345); salEmp.getCommissionRate(); System.out.print(salEmp.id); System.out.print(salEmp.weeklySalary); } Employee -name -Id +getSalary() +getName() +setID(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Answer  Which of these statements will result in compiler error? Correct them public class EmployeeDemo { public static void main(String args[]) { SalariedEmployee salEmp = new SalariedEmployee(); salEmp.calculateBonus(); salEmp.setId(12345); salEmp.getCommissionRate(); System.out.print(salEmp.Id); System.out.print(salEmp.weeklySalary); } Employee -name -Id +getSalary() +getName() +setID(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Se  The substitution principle: You can always use a subclass object when a superclass object is expected. Person Employee SalariedEmployee CommissionEmployee Employee emp = new SalariedEmployee(); Person person = new SalariedEmployee(); Try in interaction pane. Try calling some methods (e.g. setId, getId, calculateBonus)

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 You can only call methods in reference variable class(Employee) even if object is a SalariedEmployee object

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Question Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Answer Because every manager is an employee but not the other way around, the Manager class is more specialized. It is the subclass, and Employee is the superclass. Manager is a Employee (subclass)(superclass) Employee is a Manager

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Question Consider the method doSomething(Car c). List all vehicle classes from Figure 1 whose objects cannot be passed to this method. Vehicle Motorcycle Car Truck Sedan SUV

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Answer Answer: Vehicle, Truck, Motorcycle doSomething(Car c) Vehicle Motorcycle Car Truck Sedan SUV

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Writing Subclass Constructors  A subclass (E.g. Salaried employee) DOES NOT inherit constructors from its superclass  So it will need its own constructors.  Two things are done in subclass (E.g SalariedEmployee) constructor: 1.Initialize variables of superclass (likely to be private) E.g. name, id in Employee class 2.Initialize variables declared in subclass E.g. weeklySalary in SalariedEmployee class

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Writing Subclass Constructors  Say Employee class already has a 2-arg constructor:  A first attempt at writing the constructor: Is above an OK way to write subclass constructor? public class SalariedEmployee extends Employee{ double weeklySalary; public SalariedEmployee(String empName, int empId, double empWeekSal) { name = empName; id = empId; weeklySalary = empWeekSal; }... } Public class Employee{ private String name; private int id; public Employee(String name, int id){this name = name; this.id=id; } … }

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25  No. You will get compile time errors because name and id are declared private in employee class. public class SalariedEmployee extends Employee { double weeklySalary; public SalariedEmployee(String empName, int empId, double empWeekSal ) { name = empName; id = empId; weeklySalary = empWeekSal; }

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Writing Subclass Constructors  Solution: super keyword Call superclass constructor within subclass constructor E.g. SalariedEmployee constructor: public class SalariedEmployee extends Employee{ double weeklySalary; public SalariedEmployee(String empName, int empId, double empWeekSal){ super(empName, empId); weeklySalary = empWeekSal; } Super Must be the first statement in the subclass constructor

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Writing Subclass Constructors  What if subclass constructor fails to call super? Then the compiler will automatically insert super() at the beginning of the constructor. public SalariedEmployee(String empName, int empId, double empWeekSal) { weeklySalary = empWeekSal; }

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28  What if a subclass has no constructors at all? Then the compiler will create a no argument constructor in subclass that contains super(). This will be the only statement in constructor.

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Programming Question  Write a class SavingsAccount that extends the BankAccount class. In addition to the public methods and variables declared in BankAccount class, SavingsAccount class need to define following: Instance variable: interestRate Constructor that initializes interestRate and all variables in BankAccount class. Instance method: setInterestRate that set interest rate to parameter value Use BankAccount class code is in next slide 

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 public class BankAccount { private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double initialBalance) { balance = initialBalance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; } BankAccount.java

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Answer public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double balance, double interestRate) { super(balance); this.interestRate = interestRate; } public void setInterestRate(double rate) { interestRate = rate; } SavingsAccount.java

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Programming Question  Write a tester class SavingsAccountDemo to test the functionality of SavingsAccount class.  In the main method do following: Create a savings account object with balance =10000 and interest rate=2.5 Update the interest rate of savings account to 4.25 Deposit 500 Print the final balance  Sample run:

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Answer public class SavingsAccountDemo { public static void main(String args[]) { SavingsAccount savingsAcct = new SavingsAccount(10000,2.50); savingsAcct.setInterestRate(4.25); savingsAcct.deposit(500.00); System.out.println("Balance: " +savingsAcct.getBalance()); } SavingsAccountDemo.java Test it. What happens? Can we replace this statement by: BankAccount savingsAcct = new SavingsAccount(10000,2.50);

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Comment line7 You cannot call methods of subclasses from a Reference of a superclass type

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Polymorphism  Polymorphism: Ability of an object to take on many forms.  Polymorphism in OOP is achived in 2 ways: Method overloading (static polymorphism) Method overriding (dynamic polymorphism) Most common form of plymorphism

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Overloading methods  when two or more methods in the same class have the same name but different parameter types.  Called static polymorphism.  Can be determined at compile time

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Example public class Calculator { public int add(int a, int b) { return a+b; } public double add(double a, double b) { return a+b; } public int add(int a, int b, int c) { return a+b+c; } 3 overloaded and methods

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Overriding Methods  An overriding method can extend or replace the functionality of the superclass method.  Replace: provide completely different implementation  Extend: extend the functionality provided by super class

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Example calculateSalary method in Employee class overridden in both subclasses public class Employee { private String name; private int id; public Employee(String name, int id) { this.name = name; this.id = id; } public double calculateSalary() { return 2000.0; } public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } } Employee.java

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee(String empName, int empId, double weeklySalary) { super(empName, empId); this.weeklySalary = weeklySalary; } public double calculateSalary() { return this.weeklySalary*4; } public double calculateBonus() { //System.out.println("calculationg bonus of employee with name:"+getName()+" id:"+id); return this.weeklySalary*0.5; } SalariedEmployee.java Overridden implementation in SalariedEmployee subclass

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 public class CommissionEmployee extends Employee { private double grossSales; private double commissionRate; public CommissionEmployee(String empName, int empId, double grossSales, double commissionRate) { super(empName, empId); this.grossSales = grossSales; this.commissionRate = commissionRate; } public double calculateSalary() { return this.grossSales*this.commissionRate; } public double getCommissionRate() { return this.commissionRate; } } CommissionEmployee.java Overridden implementation in CommissionEmployee subclass

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Same Employee reference variable calls calculateSalary method 2 times. But execute 2 different behaviors depending on actual object it points to Calls getSalary method in SalariedEmployee class Calls getSalary method in CommissionEmployee class

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Syntax 9.2 Calling a Superclass Method Example of extending functionality of deposit method in SavingsAccount class

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Example Base implementation in superclass Extended implementation in subclass

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Question Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? a. BankAccount account = new SavingsAccount(); b. SavingsAccount account2 = new BankAccount(); c. BankAccount account = null; SavingsAccount account2 = account;

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Answer Answer: a only. Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? a. BankAccount account = new SavingsAccount(); b. SavingsAccount account2 = new BankAccount(); c. BankAccount account = null; SavingsAccount account2 = account;

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Question  What is the super class of PrintStream class in Java class library?

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Answer Class hierarchy Direct Super class of PrintStream class Subclasses of PrintStream Indirect Super classes of PrintStream class

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 ACM Java library –inheritance example

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Object: The Cosmic Superclass  The Object Class Is the (direct or indirect) Superclass of Every Java Class  Every class defined without an explicit extends clause automatically extend Object E.g. Your BankAccount class extends Object class

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 yields a string describing the object compares 2 objects with each other

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Example

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Overriding the toString Method  Override the toString method in your classes to yield a string that describes the object’s state. You already did this!  E.g. BankAccount class toString method: public String toString() { return "BankAccount[balance=" + balance + "]”; } This is overridden implementation of Object (superclass) class toString implementation

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Programming Question  Override the toString method in SavingsAccount class so that text returned include accountNumber, balance and interestRate.  Modify SavingsAccountDemo class to call toString method: public class BankAccountDemo{ public static void main(String args[]){ SavingsAccount savingsAcct = new SavingsAccount(10000,2.50); savingsAcct.setInterestRate(4.25); savingsAcct.deposit(500.00); System.out.println("Balance: " +savingsAcct); }  Sample output:

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Answer public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double balance, double interestRate){ super(balance); this.interestRate = interestRate; } public double getInterestRate() { return interestRate; } public void setInterestRate(double rate) { interestRate = rate; } public String toString(){ return super.toString() + " interestRate="+interestRate; } SavingsAccount.java

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Overriding the equals Method  equals method checks whether two objects have the same content: if (stamp1.equals(stamp2))... // Contents are the same  == operator tests whether two references are identical - referring to the same object: if (stamp1 == stamp2)... // Objects are the same

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Overriding the equals Method  To implement the equals method for a Stamp class - Override the equals method of the Object class: public class Stamp{ private String color; private int value;... public boolean equals(Object otherObject) { //your code here }... }  Cannot change parameter type of the equals method - it must be Object

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Overriding the equals Method  After casting, you can compare two Stamps public boolean equals(Object otherObject) { Stamp otherStamp = (Stamp) otherObject; //now compare this stamp object with otherStamp object }  How to compare? Check if each corresponding instance variable values are same If so, return true, Otherwise return false public boolean equals(Object otherObject) { Stamp otherStamp = (Stamp) otherObject; return this.color.equals(otherStamp.color) && this.value==otherStamp.value; }

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60  The equals method can access the instance variables of any Stamp object. public boolean equals(Object otherObject) { Stamp otherStamp = (Stamp) otherObject; return color.equals(otherStamp.color) && value == otherStamp.value; } The access otherStamp.color and otherStamp.value is legal here (ONLY in equals method)

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Programming Question  Modify BankAccount class to override equals method.  Add a tester class to call equals method: public class BankAccountDemo{ public static void main(String args[]) { BankAccount savingsAcct1 = new SavingsAccount(10000,2.50); BankAccount savingsAcct2 = new SavingsAccount(10000,2.50); System.out.println(savingsAcct.equals(savingsAcct2)); }  Sample output

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Answer public class BankAccount { private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double initialBalance) { balance = initialBalance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; } public boolean equals(Object anotherAccount) { BankAccount other = (BankAccount) anotherAccount; return (accountNumber == other.accountNumber) && (balance==other.balance); }

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Homework: Programming Question  Modify your Rectangle.java class so you override the equals method and toString method. equals method should return true only if x,y,width and height matches to rectangle in parameter. To string method should print the x,y,width and height parameters of object Sample output:

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 Answer public class Rectangle { int x, y, width, height; public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } /** * overriden equals method * */ public boolean equals(Object object) { Rectangle r = (Rectangle)object; if(x==r.x && y==r.y && width==r.width && height==r.height) return true; return false; } public String toString() { return "Rectangle [x:"+x+" y:"+y+" width:"+width+" height:"+height+"]"; } public static void main(String args[]) { Rectangle r1 = new Rectangle(10,20,50,50); Rectangle r2 = new Rectangle(10,20,50,50); Rectangle r3 = new Rectangle(10,50,50,50); System.out.println("r1= "+r1); System.out.println("r2= "+r2); System.out.println("r3= "+r3); System.out.println("r1.equals(r2)"+r1.equals(r2)); System.out.println("r1.equals(r3)"+r1.equals(r3)); }

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 The instanceof Operator  It is legal to store a subclass reference in a superclass variable: BankAccount acct1 = new SavingsAccount(1000.0, 2.5); Object obj = acct1;  Sometimes you need to convert from a superclass reference to a subclass reference. If you know a variable of type Object actually holds a SavingsAcount reference, you can cast SavingsAccount acct1 = (SavingsAccount) obj;  If obj refers to an object of an unrelated type, “class cast” exception is thrown.

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 Example : legal cast Cast obj to subclass BankAccount Cast obj to subclass SavingsAccount Since obj is pointing to a SavingsAccount object it can ONLY be safely casted to: 1.SavingsAccount 2.BankAccount OR 3.Object Same class of object type (SavingAccount) Direct/Indirect superclass of object type (SavingAccount)

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Example: illegal cast

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 The instanceof Operator  The instanceof operator tests whether an object belongs to a particular type. obj instanceof BankAccount  Using the instanceof operator, a safe cast can be programmed as follows: if (obj instanceof BankAccount) { BankAccount acct1 = (BankAccount) obj; } http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Example Direct/indirect superclasses = TRUE Same class= TRUE Direct/indirect subclasses = FALSE Any other class = FALSE

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Question Assuming that x is an object reference, what is the value of x instanceof Object?

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71 Answer Answer: The value is false if x is null and true otherwise. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 When x is null When x is not null


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance."

Similar presentations


Ads by Google