Download presentation
Presentation is loading. Please wait.
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 Fundamental Principles of OOP: - Encapsulation Encapsulation is the packing of data and functions into a single component. The features of encapsulation are supported using classes. This allow us to hide unnecessary details in our classes and provide a clear and simple interface for working with them. - Inheritance Inheritance is the process by which one object acquires the properties of another object. class hierarchies improve code readability and enable the reuse of functionality. - Polymorphism how to work in the same manner with different objects, which define a specific implementation of some abstract behavior. - Abstraction Any model that includes the most important, essential, or distinguishing aspects of something while suppressing or ignoring less important, immaterial, or diversionary detai deal with objects considering their important characteristics and ignore all other details. Classification is considered to be the most important abstraction principle.
3
Inheritance Hierarchies
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 Natural hierarchy: IS-A relation to Person class STUDENT (attributes=name, address, major | methods= toString (polymorphic), registercourse) PROFESSOR (attributes=name, address, ssn, department | methods=toSring, teachCourse) UNDRGRAD() GRADUATE(atributes= thesis topic) Some cannot be in same hierarchy: Truck Employee Sedan SUV
4
QUESTION Inheritance = IS-A relation
Which ones have inheritance relation? Which ones are the super class and subclass? Person , Student Car ,Person Car ,Vehicle
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
Inheritance Hierarchies
A subclass inherits: Superclass Non-private data attributes Superclass Non-private methods Inherited variables and methods behave as though they were declared in the subclass. A subclass does NOT inherit: Superclass constructors Superclass private variables Superclass private methods. The subclass may define additional variables and methods that were not present in the superclass. Inheritance lets you can reuse code instead of duplicating it. Employee -name -Id +getId() +getName() +calculateSalary() +setName(name) +setId(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()
7
The subclass can: Add new functionality Use inherited functionality
Override inherited functionality (modify) Employee -name -Id +claculateSalary() +getName() +setID(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()
8
The subclass can: Add new functionality Use inherited functionality
Override inherited functionality (modify) 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
9
Superclass: Employee.java public class Employee { private String name;
private int id; public double calculateSalary(){return ;} 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
10
Inheritance in java In Java, inheritance 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
11
Writing a Subclass Example
Superclass: public class Employee { private String name; private int id; public double calculateSalary(){return ;} 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 Subclass: Public class SalariedEmployee extends Employee { private double weeklySalary; public double calculateSalary(){return this.weeklySalary*4;} public double calculateBonus(){return this.weeklySalary*0.5; } } Public class SalariedEmployee extends Employee { private double weeklySalary; public double getSalary(){return this.weeklySalary*4;} public double calculateBonus(){ System.out.println(id); //Error: id has private access in Employee System.out.println(setId(10)); //Error: ONLY IF setId method has private access in Employee returnthis.weeklySalary*0.5; } SalariedEmployee.java
12
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; }
13
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; }
15
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;
16
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()
17
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()
18
Se The substitution principle:
You can always use a subclass object when a superclass object is expected. Person Try in interaction pane. Try calling some methods (e.g. setId, getId, calculateBonus) Employee SalariedEmployee CommissionEmployee Employee emp = new SalariedEmployee(); Person person = new SalariedEmployee();
19
You can only call methods in reference variable class(Employee) even if object is a SalariedEmployee object
20
Question Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?
21
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
22
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
23
Answer Answer: Vehicle, Truck, Motorcycle doSomething(Car c) Vehicle
Sedan SUV Answer: Vehicle, Truck, Motorcycle
24
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: Initialize variables of superclass (likely to be private) E.g. name, id in Employee class Initialize variables declared in subclass E.g. weeklySalary in SalariedEmployee class
25
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 Employee{ private String name; private int id; public Employee(String name, int id){this name = name; this.id=id; } … } public class SalariedEmployee extends Employee{ double weeklySalary; public SalariedEmployee(String empName, int empId, double empWeekSal) { name = empName; id = empId; weeklySalary = empWeekSal; } ...
26
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; }
27
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
28
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; }
29
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.
30
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
31
BankAccount.java 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;
32
Answer SavingsAccount.java
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;
33
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:
34
Answer SavingsAccountDemo.java Can we replace this statement by:
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()); } Can we replace this statement by: BankAccount savingsAcct = new SavingsAccount(10000,2.50); Test it. What happens?
35
You cannot call methods of subclasses from a Reference of a superclass type
Comment line7
36
Polymorphism Polymorphism: Polymorphism in OOP is achieved in 2 ways:
Ability of an object to take on many forms. Polymorphism in OOP is achieved in 2 ways: Method overloading (static polymorphism) Method overriding (dynamic polymorphism) Most common form of polymorphism
37
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
38
Example 3 overloaded and methods public class Calculator {
public int add(int a, int b) return a+b; } public double add(double a, double b) public int add(int a, int b, int c) return a+b+c; 3 overloaded and methods
39
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 BankAccount toString(){return “BankAccount balance=”+balance;} SavingsAccount toString(){ return super.toString()+ “ InterestRate=”+interestRate;}
40
Example calculateSalary method in Employee class overridden in both subclasses Employee.java 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 ; 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; }
41
Overridden implementation in SalariedEmployee subclass
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
42
Overridden implementation in CommissionEmployee subclass
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
43
Same Employee reference variable calls calculateSalary method 2 times.
Calls getSalary method in SalariedEmployee class Calls getSalary method in CommissionEmployee class Same Employee reference variable calls calculateSalary method 2 times. But execute 2 different behaviors depending on actual object it points to
44
Syntax 9.2 Calling a Superclass Method
Example of extending functionality of deposit method in SavingsAccount class
45
Example Base implementation in superclass
Extended implementation in subclass
46
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;
47
Answer 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; Answer: a only.
48
Question What is the super class of PrintStream class in Java class library? What is the parent class of Object class?
49
Answer Class hierarchy Indirect Super classes of PrintStream class
Direct Super class of PrintStream class Object=root Check any other api page for java library classes to verify this What is the parent class of Object class Subclasses of PrintStream
51
ACM Java library –inheritance example
52
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 for any object x, the expression: x.clone() != x is true We did overriding without knowing: Rectangle equals() method hashCode(): All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. Classes which provide their own implementation must override the object method public int hashCode(). The general contract for overridden implementations of this method is that they behave in a way consistent with the same object's equals() method: that a given object must consistently report the same hash value (unless it is changed so that the new version is no longer considered "equal" to the old), and that two objects which equals() says are equal must report the same hash value. There's no requirement that hash values be consistent between different Java implementations, or even between different execution runs of the same program, and while two unequal objects having different hashes is very desirable, this is not mandatory (that is, the hash function implemented doesn't need to be a perfect hash).[1] For example, the class Employee might implement its hash function by composing the hashes of its members: public class Employee { int employeeId; String name; Department dept; // other methods would be in public int hashCode() { int hash = 1; hash = hash * 17 + employeeId; hash = hash * 31 + name.hashCode(); hash = hash * 13 + (dept == null ? 0 : dept.hashCode()); return hash; }
53
compares 2 objects with each other
yields a string describing the object
54
Example
55
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 Object.toString prints class name and the hash code of the object: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like
56
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:
57
Answer SavingsAccount.java
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;
58
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
59
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
60
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 return this.color.equals(otherStamp.color) && this.value==otherStamp.value;
61
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)
62
Programming Question Modify BankAccount class to override equals method. Add a tester class to call equals method: Sample output
63
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);
64
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:
65
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)); Answer
66
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. public class BankAccountDemo{ public static void main(String args[]) { BankAccount bankAccount = new SavingsAccount(10000,2.50); Object object = new SavingsAccount(10000,2.50); object = new String("Hello"); SavingsAccount savingsAccount = (SavingsAccount)object; } *******************output********************************************** * > run BankAccountDemo java.lang.ClassCastException: java.lang.String cannot be cast to SavingsAccount at BankAccountDemo.main(BankAccountDemo.java:9) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) > **********************************************************************
67
Example : legal cast Cast obj to subclass BankAccount
SavingsAccount Since obj is pointing to a SavingsAccount object it can ONLY be safely casted to: SavingsAccount BankAccount OR Object Same class of object type (SavingAccount) Direct/Indirect superclass of object type (SavingAccount)
68
Example: illegal cast
69
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; } public class BankAccountDemo{ public static void main(String args[]) { Object object = new SavingsAccount(10000,2.50); if(object instanceof SavingsAccount) { SavingsAccount savingsAccount = (SavingsAccount)object; System.out.println("object instanceof SavingsAccount"); } if(object instanceof BankAccount) { BankAccount bankAccount = (BankAccount)object; System.out.println("object instanceof BankAccount"); if(object instanceof Object) { System.out.println("object instanceof Object"); *********************output******************* Welcome to DrJava. Working directory is /net/people/faculty/cs/rdissanayaka/CS160/s15/lec05 > run BankAccountDemo object instanceof SavingsAccount object instanceof BankAccount object instanceof Object *********************************************
70
Example Direct/indirect superclasses = TRUE Same class= TRUE
Direct/indirect subclasses = FALSE Any other class = FALSE
71
Question Assuming that x is an object reference, what is the value of x instanceof Object?
72
Answer Answer: The value is false if x is null and true otherwise.
73
When x is null When x is not null
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.