Presentation is loading. Please wait.

Presentation is loading. Please wait.

Understanding Inheritance CompSci 230 S2 2015 Software Design and Construction.

Similar presentations


Presentation on theme: "Understanding Inheritance CompSci 230 S2 2015 Software Design and Construction."— Presentation transcript:

1 Understanding Inheritance CompSci 230 S2 2015 Software Design and Construction

2 Agenda & Reading  Topics:  Inheritance  Constructors  Super & this  Method Overriding  The Object class  Method Overloading  Polymorphism  Reading  Java 2 – The Complete Reference, Chapter 8, page 193-211  The Java Tutorial :  Polymorphism Polymorphism  Overriding and Hiding Methods: Overriding  Using the Keyword supersuper 052

3 Inheritance  Inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined.  The former, known as derived classes, take over (or inherit) attributes and behaviour of the latter, which are referred to as base classes.  It is intended to help reuse of existing code with little or no modification.  Rules:  Derived class (subclass)  Inherits all the public variables and methods of a base class  Adds additional variables and methods  Can change the meaning of inherited methods (override methods) Example: Person & Employee getIRD(), getNames(): inherit from Person getSalary() – Additional method 053

4 Example: SimpleSphere & ColoredSphere  The Sphere class is a base class  Variable:  radius  Methods:  setRadius(…), diameter(), area(), circumference(), toString() … public class Sphere { protected double theRadius; public Sphere() { setRadius(1.0); } public Sphere(double r) {...} public void setRadius(double r) {...} public double radius() {... } public String toString() {...}... } public class Sphere { protected double theRadius; public Sphere() { setRadius(1.0); } public Sphere(double r) {...} public void setRadius(double r) {...} public double radius() {... } public String toString() {...}... } Example: ColoredSphere.java 054

5 Example: SimpleSphere & ColoredSphere  The ColoredSphere is a derived class that  Inherits a field (radius) from the base class,  Inherits a few methods (setRadius, diameter … etc) from the base class,  Adds a new field: color  Adds two new methods: setColour(…), getColour()  Overrides an existing method (toString) from the base class. public class ColoredSphere extends SimpleSphere { private Color color; public ColoredSphere(Color c) { super(); color = c; } public void setColor(Color c) {... } public Color getColor() {...} public String toString() { return super.toString() +...}... } public class ColoredSphere extends SimpleSphere { private Color color; public ColoredSphere(Color c) { super(); color = c; } public void setColor(Color c) {... } public Color getColor() {...} public String toString() { return super.toString() +...}... } 055

6 Constructor  A constructor in a class is a special method (function) that can be used to create objects of the class and never has a return type.  Rules:  Each Subclass constructor must always call the superclass constructor (explicitly or implicitly)  Implicitly: calls its superclass default no-argument constructor  Explicitly: using super()  If you call the superclass constructor explicitly, then the compiler will not call it implicitly. class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class B1 extends A1 { int y; public B1() { System.out.println("called B1()"); } public B1(int x, int y) { super(x); this.y = y; System.out.println("called B1(x,y)"); } class B1 extends A1 { int y; public B1() { System.out.println("called B1()"); } public B1(int x, int y) { super(x); this.y = y; System.out.println("called B1(x,y)"); } B1 b1 = new B1(); B1 b2 = new B1(10, 100); B1 b1 = new B1(); B1 b2 = new B1(10, 100); called A1() called B1() called A1(x) called B1(x,y) Example: B1.java Calls constructor implicitly Calls constructor explicitly 056

7 Constructor  Rules:  A subclass cannot inherit constructors from the base class. Each subclass should define its constructor  If no constructor is defined, the compiler adds a single zero-parameter default constructor for the class and applies the default initialization for any data fields. class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class B2 extends A1 { int y = 10; } class B2 extends A1 { int y = 10; } B2 b = new B2(); System.out.println("b.x=" + b.x); System.out.println("b.y=" + b.y); B2 b = new B2(); System.out.println("b.x=" + b.x); System.out.println("b.y=" + b.y); called A1() b.x=1 b.y=10 Example: B2.java Calls base class’s constructor implicitly Add a single zero-parameter default constructor B2 b = new B2(10); Compile time error - No constructor with an integer argument class B extends A1 { int y = 10; public B(int x) { super(x); } class B extends A1 { int y = 10; public B(int x) { super(x); } B b = new B(); Compile time error - No zero-parameter constructor 057

8 Constructor  Rules:  You can only call a superclass constructor from a subclass constructor, not from any other subclass method  Never place any subclass constructor code ahead of its superclass constructor call (reason: a subclass constructor’s initialisation may depend on the values declared in a superclass) class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class A1 { int x; public A1() { x=1; System.out.println("called A1()"); } public A1(int x) { this.x = x; System.out.println("called A1(x)"); } class B3 extends A1 { int y = x + 10; public B3(int x) { super(x); } class B3 extends A1 { int y = x + 10; public B3(int x) { super(x); } B3 b = new B3(100); System.out.println("b.x=" + b.x); System.out.println("b.y=" + b.y); B3 b = new B3(100); System.out.println("b.x=" + b.x); System.out.println("b.y=" + b.y); called A1(x) b.x=100 b.y=110 Example: B3.java 058

9 public, private & protected  Classes, and their fields and methods have access levels to specify how they can be used by other objects during execution  A private field or method is accessible only to the class in which it is defined.  A protected field or method is accessible to the class itself, its subclasses,  A public field or method is accessible to any class of any parentage in any package 059

10 public, private & protected  Example: public class Sphere { protected double theRadius; public Sphere() { setRadius(1.0); } public Sphere(double r) {...} public void setRadius(double r) {...} public double radius() {... } public String toString() {...}... } public class Sphere { protected double theRadius; public Sphere() { setRadius(1.0); } public Sphere(double r) {...} public void setRadius(double r) {...} public double radius() {... } public String toString() {...}... } public class ColoredSphere extends SimpleSphere { private Color color; public ColoredSphere(Color c) { super(); color = c; } public void setColor(Color c) {... } public Color getColor() {...} public String toString() { return super.toString() +...}... public void method1() { System.out.println(super.theRadius); } public class ColoredSphere extends SimpleSphere { private Color color; public ColoredSphere(Color c) { super(); color = c; } public void setColor(Color c) {... } public Color getColor() {...} public String toString() { return super.toString() +...}... public void method1() { System.out.println(super.theRadius); } 0510

11 Usage of super & this  super  Constructor : super() or super(…)  Automatically called in derived constructor if not explicitly called  Call to super() must be the first call in constructor  Cannot call super.super()  super.member  Members can be either method or instance variables  Refers to the members of the superclass of the subclass in which it is used  Note: a variable that has the same name as a variable in the superclass hides the superclass's member variable. The variable in the superclass cannot be referenced by its name and it must be accessed through “super” (later this week)  Used from anywhere within a method of the subclass  this  Can be used inside any method to refer to the current object  Constructor: this(), this(…): refer to its constructor  this.member  Members can be either method or instance variables  this.instance_variable:  To resolve name-space collisions that might occur between instance variables and local variables 0511

12 Method Overriding  If an inherited property or method needs to behave differently in the derived class it can be overridden; that is, you can define a new implementation of the method in the derived class.  You can change the meaning (override) of the method declared in the superclass  Completely, or  Add more functionality to the method  The new method can call the original method in the parent class by specifying Super before the method name.  Rules:  A Subclass cannot override final methods declared in the base class.  The Overridden method must have the same arguments as the inherited method from the base class. class Base2 { public final void finalMethod() { System.out.println("called Base:finalMethod"); } class Base2 { public final void finalMethod() { System.out.println("called Base:finalMethod"); } public class Derived2 extends Base2 { public final void finalMethod() { System.out.println("called Derived:finalMethod");... public class Derived2 extends Base2 { public final void finalMethod() { System.out.println("called Derived:finalMethod");... Final methods cannot be overridden. Example: Derived2.java 0512

13 Overriding class Base { public void aMethod() { System.out.println("called Base:aMethod"); } class Base { public void aMethod() { System.out.println("called Base:aMethod"); } public class Derived extends Base { public void aMethod() { System.out.println("called Derived:aMethod"); } public static void main(String[] args) { Derived d = new Derived(); d.aMethod(); } public class Derived extends Base { public void aMethod() { System.out.println("called Derived:aMethod"); } public static void main(String[] args) { Derived d = new Derived(); d.aMethod(); } called Derived:aMethod Example: Derived.java This method defined by the subclass is overridden to the method defined in the superclass. class Base { public void add() { System.out.println("called Base:add"); } class Base { public void add() { System.out.println("called Base:add"); } public class Derived extends Base { public void add() { super.add(); System.out.println("called Derived:add"); } public static void main(String[] args) { Derived d = new Derived(); d.add(); } public class Derived extends Base { public void add() { super.add(); System.out.println("called Derived:add"); } public static void main(String[] args) { Derived d = new Derived(); d.add(); } Use super.methodName() to call the method defined in the superclass 0513

14 The Object class  Every java class has Object as its superclass and thus inherits the Object methods.  Object is a non-abstract class  Many Object methods, however, have implementations that aren’t particularly useful in general  In most cases it is a good idea to override these methods with more useful versions.  equals: compares two objects for equality and returns true if they are equal.  toString: returns a String representation of the object Object … public class Object {... public boolean equals(Object obj) { return (this == obj); } public String toString() { return getClass().getName()... } public class Object {... public boolean equals(Object obj) { return (this == obj); } public String toString() { return getClass().getName()... } 0514

15 The toString() method  It is intended to return a readable textual representation of the object upon which it is called. This is great for debugging!  Every class has a toString, even if it isn't in your code.  The default toString returns the class's name followed by a hexadecimal (base-16) number  Replace the default behaviour by overriding the toString method in your class System.out.println(someObject); public String toString() { return "(" + x + ", " + y + ")"; } public String toString() { return "(" + x + ", " + y + ")"; } 0515

16 The equals() method  By default, equals(Object o) does exactly what the == operator does – compare object references  That is, two object are the same if the point to the same memory.  Since java does not support operator overloading, you cannot change this operator.  However, the equals method of the Object class gives you a chance to more meaningful compare objects of a given class.  returns true if they are actually the same object Sphere sphere1 = new Sphere(); Sphere sphere2 = sphere1; if (sphere1.equals(sphere2)) { System.out.println("same"); } else { System.out.println("different"); } Sphere sphere1 = new Sphere(); Sphere sphere2 = sphere1; if (sphere1.equals(sphere2)) { System.out.println("same"); } else { System.out.println("different"); } Sphere sphere1 = new Sphere(2.0); Sphere sphere3 = new Sphere(2.0); if (sphere1.equals(sphere3)) { System.out.println("same"); } else { System.out.println("different"); } Sphere sphere1 = new Sphere(2.0); Sphere sphere3 = new Sphere(2.0); if (sphere1.equals(sphere3)) { System.out.println("same"); } else { System.out.println("different"); } same different 0516

17 The customize equals method  To override, simply override method with version that does more meaningful test, i.e. compares values and returns true if equal, false otherwise  E.g. An equals methods that determines whether two sphere have the same radius public boolean equals(Object rhs) { return (rhs instanceof MySphere) && (theRadius == ((MySphere) rhs).radius()); } public boolean equals(Object rhs) { return (rhs instanceof MySphere) && (theRadius == ((MySphere) rhs).radius()); } MySphere sphere1 = new MySphere(); MySphere sphere2 = sphere1; if (sphere1.equals(sphere2)) { System.out.println("same"); } else { System.out.println("different"); } MySphere sphere1 = new MySphere(); MySphere sphere2 = sphere1; if (sphere1.equals(sphere2)) { System.out.println("same"); } else { System.out.println("different"); } same MySphere sphere1 = new MySphere(2.0); MySphere sphere3 = new MySphere(2.0); if (sphere1.equals(sphere3)) { System.out.println("same"); } else { System.out.println("different"); } MySphere sphere1 = new MySphere(2.0); MySphere sphere3 = new MySphere(2.0); if (sphere1.equals(sphere3)) { System.out.println("same"); } else { System.out.println("different"); } same 0517

18 Method Overloading  Method overloading is the process of using the same method name for multiple methods  The signature of each overloaded method must be unique  The signature includes the number, type, and order of the parameters  The return type of the method is NOT part of the signature  The compiler must be able to determine which version of the method is being invoked by analysing the parameters public void aMethod() { System.out.println("called aMethod()"); } public void aMethod() { System.out.println("called aMethod()"); } public void aMethod(int x, String y, boolean z) { System.out.println("called aMethod(int x, String y, boolean z)"); } public void aMethod(int x, String y, boolean z) { System.out.println("called aMethod(int x, String y, boolean z)"); } public void aMethod(String y, int x, boolean z) { System.out.println("called aMethod()"); } public void aMethod(String y, int x, boolean z) { System.out.println("called aMethod()"); } Zero-parameter 3-parameters (int, String, boolean) 3-parameters (String, int, boolean) public int aMethod(int x, String y, boolean z) {... public int aMethod(int x, String y, boolean z) {... Example: Overload.java Not Overloaded error: aMethod(int,String,boolean) is already defined in… 0518

19 Types  We can create an instance in the following way:  An ColoredSphere object is also an Sphere object and it is also an Object. Therefore, we can assign … Sphere ColoredSphere ColoredSphere s1 = new ColoredSphere(Color.blue); Type of the variable (LHS) = type created of the ColoredSphere created (RHS) Sphere s2 = new ColoredSphere(Color.green); Object obj1 = new ColoredSphere(Color.red); Sphere s2 = new ColoredSphere(Color.green); Object obj1 = new ColoredSphere(Color.red); System.out.println(s1); // call the toString() from ColoredSphere System.out.println(s2); // call the toString() from ColoredSphere System.out.println(obj1); // call the toString() from ColoredSphere Sphere s3 = new Sphere(10); System.out.println(s3); //call the toString() from Sphere System.out.println(s1); // call the toString() from ColoredSphere System.out.println(s2); // call the toString() from ColoredSphere System.out.println(obj1); // call the toString() from ColoredSphere Sphere s3 = new Sphere(10); System.out.println(s3); //call the toString() from Sphere 0519

20 Polymorphism  This occurs when one method name in a method call can cause different actions depending on which type of instance is invoking the method. !  At runtime, the actual method corresponding to the instance type is executed (i.e., the method defined in the class whose constructor created the object):! Sphere ColoredSphere System.out.println(s1); // call the toString() from ColoredSphere System.out.println(s2); // call the toString() from ColoredSphere System.out.println(obj1); // call the toString() from ColoredSphere Sphere s3 = new Sphere(10); System.out.println(s3); //call the toString() from Sphere System.out.println(s1); // call the toString() from ColoredSphere System.out.println(s2); // call the toString() from ColoredSphere System.out.println(obj1); // call the toString() from ColoredSphere Sphere s3 = new Sphere(10); System.out.println(s3); //call the toString() from Sphere 0520

21 Polymorphism  Definition:  Polymorphism is the ability of objects belonging to different types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behaviour. The program does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called late binding or dynamic binding).  Example:  Classes:  Kitchen  Person  HouseWife  PizzaChef  KFCChef  TakeAwayChef 0521

22 Example  Our COMPSCI230Kitchen has a Person  A person has surname and first name  Create a person in our COMPSCI230Kitchen  Person  Instance variables: surname and first name  Methods:  getName() get surname and first name  cookDinner() to prepare food for dinner  An ordinary person prepares dinner using microwave! Person HouseWife KFCChef PizzaChefTakeAwayChef Kitchen public class Person { String surname; String firstname;... public void cookDinner() { System.out.println("Microwave Dinner"); } public class Person { String surname; String firstname;... public void cookDinner() { System.out.println("Microwave Dinner"); } Person p = new Person(); System.out.println(p.getName()); p.cookDinner(); Person p = new Person(); System.out.println(p.getName()); p.cookDinner(); getName cookDinner 0522

23 HouseWife  Now our COMPSCI230Kitchen has a houseWife person  HouseWife  Inherited method: getName  To get her name  Additional method: cleanKitchen  To clean our kitchen  Overridden method: cookDinner  To cook food for dinner  A housewife makes Roast chicken with Potato. p = new HouseWife(); getName cookDinner cleanKitchen public class HouseWife extends Person { public HouseWife(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Roast Chicken with Potato"); } public void cleanKitchen() { System.out.println("Cleaning now"); } public class HouseWife extends Person { public HouseWife(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Roast Chicken with Potato"); } public void cleanKitchen() { System.out.println("Cleaning now"); } System.out.println(p.getName()); p.cookDinner(); System.out.println(p.getName()); p.cookDinner(); Person HouseWife 0523

24 PizzaChef  Now our COMPSCI230Kitchen has a PizzaChef person  PizzaChef  Inherited method: getName  To get her name  Overridden method: cookDinner  To cook food for dinner  A pizzachef makes Pizza Person PizzaChef p = new PizzaChef(); public class PizzaChef extends Person { public PizzaChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Pizza"); } public class PizzaChef extends Person { public PizzaChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Pizza"); } System.out.println(p.getName()); p.cookDinner(); System.out.println(p.getName()); p.cookDinner(); 0524

25 KFCChef  Now our COMPSCI230Kitchen has a KFCChef person  KFCChef  Inherited method: getName  To get her name  Overridden method: cookDinner  To cook food for dinner  A KFCChef makes KFC fried chicken Person kFCChef p = new KFCChef(); public class KFCChef extends Person { public KFCChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("KFC Chicken"); } public class KFCChef extends Person { public KFCChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("KFC Chicken"); } System.out.println(p.getName()); p.cookDinner(); System.out.println(p.getName()); p.cookDinner(); 0525

26 TakeAwayChef  Now our COMPSCI230Kitchen has a TakeAwayChef person  TakeAwayChef  Inherited method: getName  To get her name  Overridden method: cookDinner  To cook food for dinner  A TakeAwaychef makes fried rice Person TakeAwayChef p = TakeAwayChef(); public class TakeAwayChef extends Person { public TakeAwayChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Fried Rice"); } public class TakeAwayChef extends Person { public TakeAwayChef(String firstname, String surname) { super(firstname, surname); } public void cookDinner() { System.out.println("Fried Rice"); } System.out.println(p.getName()); p.cookDinner(); System.out.println(p.getName()); p.cookDinner(); 0526

27 An array of Person  The array holds five objects of type Person.  Because of their inheritance relationship with the Person class, the HouseWife, PizzaChef, KFCChef and TakeAwayChef classes can be assigned to the array.  Within the for-loop, the cookDinner method is invoked on each element of the array.  At first, when a method call is executed, the object is checked first and if the method does not exist, then check the superclass (work from the child to the parent class) – Type checking is done at compile time  Next, the method is executed based on the object, not on the type of variable. The derived classes override the cookDinner method of the Person class. This makes the overridden cookDinner() methods of the derived classes execute when the cookDinner() method is called using the base class reference from the array Person[] pList = new Person[5]; pList[0] = new Person("Dick", "Smith"); pList[1] = new HouseWife("Theresa", "Thompson"); pList[2] = new PizzaChef("Michael", "Hill"); pList[3] = new KFCChef("Peter", "Wong"); pList[4] = new TakeAwayChef("Kevin", "Chan"); for (int i=0; i<pList.length; i++) pList[i].cookDinner(); Person[] pList = new Person[5]; pList[0] = new Person("Dick", "Smith"); pList[1] = new HouseWife("Theresa", "Thompson"); pList[2] = new PizzaChef("Michael", "Hill"); pList[3] = new KFCChef("Peter", "Wong"); pList[4] = new TakeAwayChef("Kevin", "Chan"); for (int i=0; i<pList.length; i++) pList[i].cookDinner(); The result depends on the object stored, not on the type of the variable. Example:Kitchen.java 0527

28 Rules  Polymorphism is the ability of objects belonging to different types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behaviour.  At Compile time,  the type of each variable is checked to ensure that only methods belonging to that type are called  At Run time,  the code executed depends on the nature of the object, not the type of the variable. HouseWife w; w = new HouseWife("Theresa", "Thompson"); w.cookDinner(); w.cleanKitchen(); Person p1; p1 = new HouseWife("Theresa", "Thompson"); p1.cookDinner(); //p1.cleanKitchen(); //Compile error HouseWife w; w = new HouseWife("Theresa", "Thompson"); w.cookDinner(); w.cleanKitchen(); Person p1; p1 = new HouseWife("Theresa", "Thompson"); p1.cookDinner(); //p1.cleanKitchen(); //Compile error No cleanKitchen method declared in Person class. 0528

29 Review  Except for the Object class, a class has exactly one direct superclass.  A class inherits fields and methods from all its superclasses, whether direct or indirect.  Overloading VS Overriding  Same method name & … Within a classParent & Child class Same method signatureCompile-time errorOverriding different method signatureOverloading 0529


Download ppt "Understanding Inheritance CompSci 230 S2 2015 Software Design and Construction."

Similar presentations


Ads by Google