1 / 85

Chapter 13

Chapter 13. Inheritance , interface and Polymorphism. Chapter 13 Objectives. Understanding inheritance and polymorphism. Write programs that are easily extensible and modifiable by applying polymorphism in program design.

donald
Download Presentation

Chapter 13

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13 Inheritance, interface and Polymorphism

  2. Chapter 13 Objectives • Understanding inheritance and polymorphism. • Write programs that are easily extensible and modifiable by applying polymorphism in program design. • Define reusable classes based on inheritance and abstract classes and abstract methods. • understand and know how to use all java visibility modifiers • private, package, protected, public. • Understand java interfaces • Differentiate the abstract classes and Java interfaces.

  3. Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called the child class or subclass. • The child class inherits characteristics (data & methods) of the parent class • That is, the child class inherits the methods and fields defined for the parent class 2

  4. Defining Classes with Inheritance • Case Study: • Implement a class roster that contains both undergraduate and graduate students. • Each student’s record will contain • his or her name, • three test scores, and • the final course grade. • The formula for determining the course grade is different for graduate students than for undergraduate students.

  5. Modeling Two Types of Students • Two possible ways to design the classes: • Define two unrelated classes, one for undergraduates and one for graduates. • Define three classes, one (superclass) for the common part of both kinds of students, and one (subclass) for either kind of students. Either subclass need only describe those parts of the kind of students it describes which were not described in the common part class. --- Programming by difference

  6. Classes for the Class Roster • For the Class Roster sample, we design three classes: • Student • UndergraduateStudent • GraduateStudent • The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects. • The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects.

  7. Inheritance Hierarchy

  8. Animal Mammal Bird Horse Bat Parrot Class Hierarchies (Further Example ) • A child class of one parent can be the parent of another child, forming class hierarchies

  9. The Object Class • A class called Object is defined in the java.lang package, • All objects are derived from the Object class • If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class • The Object class is therefore the ultimate root of all class hierarchies • The Object class contains a few useful methods, such as toString(),equals(),hashCode() which are inherited by all classes. • You may choose to override equals and/or toString to define equality/toString in your way. 13

  10. Single vs. Multiple Inheritance • Java supports single inheritance, meaning that a child class can have only one parent class • Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents • Collisions, such as the same variable name in two parents, have to be resolved • In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overhead.

  11. The Protected Modifier • The modifier protected makes a data member or method visible and accessible to • the class where the member is defined and • the descendant classes

  12. Visibility modifiers and their usage The visibility modifiers determine which class members can be referenced from where and which cannot. • public members: • all classes • protected members • all classes in the same package + • all subclasses (and subsubclasses …) • Note: Java has no notions of public, private or protected inheritance as in C++; all inheritances are public. • package members [default visibility] • all classes in the same package • private members • can only be used in the same class where the member is defined.

  13. Visible regions for members of class A visible region for pubic members [of class A] visible region for protected members package a.b.c visible region for package members package a.b.c; public class A { public int p1… protected int p2… int p4; //package scope private int p3 … } package a.b.c package a.b.c … extend A visible region for private members of class A extend A extend A extend A

  14. Inheritance and Member Accessibility • We use the following visual representation of inheritance to illustrate data member accessibility.

  15. The Effect of Three Visibility Modifiers

  16. Accessibility of Super from Sub • Everything except the private members of the Super class is visible from a method of the Sub class.

  17. Kinds of APIs • Application Programming Interface (API ) • Client’s API • see only public classes and class members • Developer’s API • client’s API + protected class/class members • Implementer or hacker’s API • See all. • Developer’s API + private/package class/members.

  18. Types of Objects and Variables • The (actual) type of an object is the class that is referred to when it is created via the “new” operation. • Student s1 = new Student(“name”, age, sex); • Two types associated with variables ( including method parameters/fields): • The declared type of a variable is the type referred to in its declaration (also: declared class; compile-time type) • Person p1, p2 = new Person(…) ; • The actual type of a variable is the type of the object bound to the variable at a specific moment during program execution (also: run-time type) • p1 = s1 ; • Note: the declared type of a variable is static(i.e., unchangable ) once it is declared, while the actual type of a variable is dynamic (i.e., can be changed and known until runtime). • p2 = s1;

  19. Example: Declared type and actual type

  20. Example: Actual type • A variable can have multiple actual types during its life time • A variable’s actual types can be known until runtime.

  21. Signature of a method or constructor • The signature of a method or constructor: … returnTypeoptm(Type1 arg1,…, Typen argn) throws Exception1,…,Exceptionm { … } is the list [m, Type1, …, Typen] • Notes: return type, parameter name and exceptions are not part of method signature. 8

  22. SuperClass int f1 ; # int m1() SubClass int f1 ; + int m1() Redefinitions of methods/constructors in subclass • We say an instance method m1 (or constructor) of a super class P is overridden by an instance method m2 (or constructor) of a child class C iff • m1 and m2 have the same signature, • m1 is not private (nor static), • m2 has the same or more open visibility. • notes: • public(+) > protected(#) > package (default) • It is illegal that m2 less visibile than m1. • (e.g., m1 is + but m2 is #).

  23. Examples (x ;illegal) (two mistakes here)

  24. Redefinitions of fields in subclass • We say an instance field f1 (or constructor) of a super class P is shadowed by an instance field f2 of a child class C iff • m1 and m2 have the same name, • m1 is not private (nor static), • notes: • Essentially there is no restriction on • fields with the same name. • It is legal that m2 less visibile than m1. • It is also legal that m1 and m2 • have different types

  25. Examples (0 ;illegal) (No mistake here)

  26. Overriding and Shadowing handling • What happens if both parent and child class contains members of the same name or signature ? • fields => variable shadowing; • constructor => impossible! • methods => methods overriding

  27. Method Overriding (continued) • The actual type (not casted type) of an object determines which method is invoked • This mechanism : ( • variables enabling different actual types + • actual type determine which method is invoked ) is called polymorphism.

  28. Pet myPet; // declared type myPet = new Dog(); // actual type . . . myPet = new Cat(); Polymorphism Example • Java allows a single variable to refer to objects of different subtypes of the declared type of the variable. • For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: • Actual type must be the declared type or a subtype of the declared type.

  29. Student roster = new Student[40]; . . . roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent(); . . . Creating the roster Array • We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes.

  30. State of the roster Array • The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.

  31. for(Student student : roster) { student.computeCourseGrade(); } Sample Polymorphic Message • To compute the course grade using the roster array, we execute • If student refers to a GraduateStudent, then the computeCourseGrade method of the GraduateStudent class is executed. • If student refers to an UndergraduateStudent, then the computeCourseGrade method of the UndergraduateStudent class is executed. • Note: It is the actual type (a runtime property) instead of declared type that determines which method to be executed.

  32. intundergradCount = 0; for(int i = 0; i < numberOfStudents; i++) { if(roster[i] instanceofUndergraduateStudent) { undergradCount++; } } The instanceof Operator • The instanceof operator can help us learn the class (actual type) of an object. • The following code counts the number of undergraduate students.

  33. class Messages { public static void main (String[] args) { Message m = new Message(); Advice a = new Advice(); m.message(); a.message(); (Message a).message() // same as a.message() } } // class Messages class Message { public void message() { System.out.println (”Message"); } } // class Thought class Advice extends Message { public void message() { // overriding method System.out.println (”Advice"); } } // class Advice More Example

  34. Overloading vs. Overriding • Don‘t confuse the concepts of overloading (多載) and overriding(覆蓋) • Overloading deals with multiple methods in the same class with the same name but different signatures • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overloading lets you define a similar operation in different ways for different data • Overriding lets you define a similar operation in different ways for different object types 9

  35. Inheritance and Constructors • Constructors of a superclass are not inherited by its subclasses. • You must define a constructor for a class or • use the default constructor public <className>() {} added by the compiler. • The statement super(...); can be used to call the superclass’s constructor. • use it to reuse super class’s constructs. • must be the first statement in the body. • No“extends’ clause used, then superclass is assumed to be theObject class. … class A { …} means … class A extends Object {…}

  36. Example public class Circle { public double x, y, r; // instance variables // ncircles is class variable public static int ncircles = 0; // Constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; ncircles++; } public Circle(double r) { this(0.0,0.0, r ) ; ncircles++; } ...}

  37. Subclass Example • The class GraphicCircle: public class GraphicCircle extends Circle { // Extra fields Color outline, fill; // Extra constructors public GraphicCircle(Color edge, Color fill) { x = 0.0; y = 0.0; r = 1.0; outline = edge; this.fill = fill; } public GraphicCircle(double r, Color edge, Color fill) { super(r); outline = edge; this.fill = fill; } // Extra methods public void draw(Graphics g) { g.setColor(outline); g.drawOval(x-r, y-r, 2*r, 2*r); g.setColor(fill); g.fillOval(x-r, y-r, 2*r, 2*r); } }

  38. The super Reference Revisited • Inherited parent methods/fields can be explicitly invoked using the super reference • If a method is declared with the final modifier, it cannot be overridden • c.f: a final field cannot be modified!. • The concept of overriding can be applied to data (called shadowing variables), but shadowing behaves quite differently from overriding. • The syntax of super is: super.method (parameters) super.var 10

  39. Shadowing superclass fields vs overriding superclass methods ((A) c).m() ; // m() in A ? no !! super.m(); // m() in B ((B) this).m(); // m() in C ((A) this).m(); // m() in C ((A) c).m(); ((B) c).m(); m(); // m() in C class A { int x ; int m() …} class B extends A { int x; int m() …} class C extends B { int x; // x in B and A are shadowed // by this.x int m() {…} // m() overrides m() in A & B C c = new C(); … x, this.x // field x in C super.x, ((B) this).x // field x in B ((A) this).x // filed x in A super.super.x // syntax error!! c.x // field in C ((B)c).x // fields in B ((A)c).x // fields in A

  40. class Firm { public static void main (String[] args) { Manager sam = new Manager ("Sam", "123 Main Line", "555-0469", "123-45-6789", 1923.07); Employee carla = new Employee ("Carla", "456 Off Line", "555-0101", "987-65-4321", 846.15); Employee woody = new Employee ("Woody", "789 Off Rocker", "555-0000", "010-20-3040", 769.23); woody.print(); out.println ("Paid: " + woody.pay()); System.out.println(); carla.print(); out.println ("Paid: " + carla.pay()); System.out.println(); sam.print(); sam.awardBonus (2000); out.println ("Paid: " + sam.pay()); System.out.println(); } }

  41. class Employee { protected String name, address, phone, ID; protected double salary; public Employee (String name, String address, String phone, String ID, double salary) { this.name = name; this.address = address; this.phone = phone; this.payRate = payRate; this.ID = ID; } // constructor Employee public double pay () { return salary; } // method pay public void print () { System.out.println (name + " " + ID); System.out.println (address); System.out.println (phone); } } // class Employee

  42. class Manager extends Employee { private double bonus; public Manager (String name, String address, String phone, String ID, double pay) { super (name, nddress, phone, ID, pay);// call parent’s constructor bonus = 0; // bonus yet to be awarded } public void awardBonus (double bonus) { this.bonus = bonus; } public double pay () { // managers need special way to count pay! double pay = super.pay() + bonus; // call parent’s method bonus = 0; return pay; } }

  43. Abstract Superclasses and Abstract Methods • When we define a superclass, we often do not need to create any instances of the superclass. • We want use instances of its subclasses only. • Ex: class Shape { • double area() ; • double cricumference(); … • } • class Rectangle extends Shape {…} • class Ellipse extends Shape { … } • Depending on whether we need to create instances of the superclass, we must define the class differently.

  44. Definition: Abstract Class • An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body. • Private methods and static methods may not be declared abstract. • An abstract class is a class which is defined with the modifier abstractand/or • contains zero or more abstract methods OR • that does not provide an implementation of an inherited abstract method. • No instances can be created from an abstract class. • If A in an abstract class, then it is illegal to use new A(…).

  45. Abstract Classes revisted • An abstract class is a placeholder in a class hierarchy that represents a generic concept • An abstract class cannot be instantiated • We use the modifier abstract on the class header to declare a class as abstract • An abstract class often contains abstract methods (like an interface does), though it doesn’t have to

  46. Abstract Classes • The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract • An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet) • The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

  47. Case 1 • Student Must Be Undergraduate or Graduate • If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent. • Therefore, we must define the Student class so that no instances may be created of it.

  48. Case 2 • Student Does Not Have to Be Undergraduate or Graduate. • In this case, we may design the Student class in one of two ways. • We can make the Student class instantiable. • We can leave the Student class abstract and add a third subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories.

  49. Which Approach to Use • The best approach depends on the particular situation. • When considering design options, we can ask ourselves which approach allows easier modification and extension.

  50. Interfaces • A Java interface is a collection of abstract methods and constants • An abstract method is a method header without a method body (i.e., no implementation) • An abstract method in an interface can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off. • cf: abstract methods in an abstract class must be declared explicitly using the abstract modifier. • An interface is used to formally define a set of methods that a class will implement

More Related