Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC 233 Tutorial 13 March 11/12th, 2015.

Similar presentations


Presentation on theme: "CPSC 233 Tutorial 13 March 11/12th, 2015."— Presentation transcript:

1 CPSC 233 Tutorial 13 March 11/12th, 2015

2 Upcasting Because the relationship between child and parent class is “is a”, an instance of child classes can be treated as an instance of the parent class. Person Note: I omit the attributes and methods of Person and Student in purpose. They are the same as those defined in Tutorial 13. Person has an attribute name while Student has an additional attribute university. Person p1 = new Person(“Foo”); Person p2 = new Student(“Foo”, “UoC”); Student 2

3 Dynamic Binding Given a class hierarchy and a method definition, what is the output or which class’s toString is called? Person public String toString(){ return “I am a person”; } public void print(Person p){ System.out.println(p); } Answer: we don’t know because we don’t know which class’s instance is passed as the parameter. We could know the information only in runtime. Student public String toString(){ return “I am a student”; } 3

4 Dynamic Binding public static void main(String[] args){
Person p1 = new Person(“John”); Person p2 = new Student(“Jack”,”UoC”); print(p1); print(p2); } public static void print(Person p){ System.out.println(p); We could ask student the outputs of the 1st and 2nd print which are “I am a person” and “I am a student”, respectively. 4

5 Exercise Given a base class Operator, define three subclasses called Addition, Subtraction, Multiplication. Override the public int compute(int left, int right) Override the public String getFormula(int left, int right, int result) 5

6 Exercise Add a fourth sub-class Division
Override the public int compute(int left, int right) Override the public String getFormula(int left, int right, int result) Change the getOperator method to return an instance of Division when “/” is input.

7 Advantage When an operator is deleted or a new operator is added, the code of main keeps stable.


Download ppt "CPSC 233 Tutorial 13 March 11/12th, 2015."

Similar presentations


Ads by Google