inheritance and polymorphism. objectives – define inheritance, overriding methods and...

of 40 /40
Inheritance and Polymorphism

Author: oswin-boone

Post on 18-Dec-2015

220 views

Category:

Documents


0 download

Embed Size (px)

TRANSCRIPT

  • Slide 1
  • Inheritance and Polymorphism
  • Slide 2
  • Objectives Define inheritance, overriding methods and polymorphism. Define reusable classes based on inheritance and abstract classes and abstract methods. Define methods, using the protected modifier. Describe the concepts of constructor in inheritance. Write programs that are easily extensible and modifiable by applying polymorphism in program design.
  • Slide 3
  • Inheritance Software reusability Create new class from existing class Absorb existing classs data and behaviors Enhance with new capabilities Subclass extends superclass Subclass More specialized group of objects Behaviors inherited from superclass Can customize Additional behaviors
  • Slide 4
  • Inheritance To design two or more entities that are different but share many common features. Steps : 1.Define a class that contains the common feature of the entities 2.Define classes as an extension of common class inheriting everything form the common class Notes : Common class = superclass, ancestor, base class Class inherit = subclasses ; descendant; derived class
  • Slide 5
  • Examples
  • Slide 6
  • Example Employee +name : String +salary : double +birthDate : Date +getDetails () : String public class Manager{ public String name; public double salary; public Date birthDate; public String department; public void getDetail(){ //... } Manager +name : String +salary : double +birthDate : Date +department : String +getDetails () : String public class Employee{ public String name; public double salary; public Date birthDate; public void getDetail(){ //... }
  • Slide 7
  • Inheritance Concept Employee Manager +name : String +salary : double +birthDate : Date +getDetails () : String +department : String Java programming language allows a class to extend only one other class When a class inherits from only one class, it is called single inheritance For multiple inheritance (inherits more than one classes) must used interfaces
  • Slide 8
  • Inheritance Syntax public class Employee{ public String name; public double salary; public Date birthDate; public void getDetail(){ //... } public class Manager extends Employee{ public String department; } Employee Manager +name : String +salary : double +birthDate : Date +getDetail () : String +department : String class extends { // }
  • Slide 9
  • Employee Engineer Manager Director + carAllowance : double + inceaseAllowance() name : String salary : double birthDate : Date getDetail () : String Inheritance Tree +department : String
  • Slide 10
  • Another example Case Study: Suppose we want implement a class roster that contains both undergraduate and graduate students. Each students 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.
  • Slide 11
  • Type of StudentGrading System Undergraduatepass if (test1+test2+test3/3) >=70 Graduatepass if (test1+test2+test3/3) >=80 Steps: 1.Define two unrelated classes for undergraduate and graduate students 2.Define entities that share common data or behavior (avoid duplication) 3.Design these two classes using inheritance 4.Define 3 classes 1.Student (class to incorporate behavior and data common to both graduate and undergraduate 2.GraduateStudents (class to incorporate behavior specific to graduate students) 3.UndergraduateStudents (class to incorporate behavior specific to undergraduate students) Defining Classes with Inheritance
  • Slide 12
  • Modeling Two Types of Students There are two ways to design the classes to model undergraduate and graduate students. We can define two unrelated classes, one for undergraduates and one for graduates. We can model the two kinds of students by using classes that are related in an inheritance hierarchy. Two classes are unrelated if they are not connected in an inheritance relationship.
  • Slide 13
  • 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.
  • Slide 14
  • Inheritance Hierarchy
  • Slide 15
  • The Protected Modifier The modifier protected makes a data member or method visible and accessible to the instances of the class and the descendant classes. Intermediate level of protection between public and private. Public data members and methods are accessible to everyone. Private data members and methods are accessible only to instances of the class.
  • Slide 16
  • Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. Class Hierarchy This shows the inherited components of the superclass are part of the subclass instance Instances
  • Slide 17
  • The Effect of Three Visibility Modifiers
  • Slide 18
  • Accessibility of Super from Sub Everything except the private members of the Super class is visible from a method of the Sub class.
  • Slide 19
  • Accessibility from Another Instance Data members accessible from an instance are also accessible from other instances of the same class.
  • Slide 20
  • Accessibility ModifierSame class Same Package SubclassUniverse privateYes defaultYes protectedYes publicYes
  • Slide 21
  • Overriding Method A subclass can modify behavior inherited form parent class A subclass can create a method with different functionality than the parents method but with the same: > name > return type > argument list Overriding is to adding additional features; modify existing behavior.
  • Slide 22
  • Rules About Overriding Method Must have a return types that is identical to the method it overrides Cannot be less accessible that the method it overrides. When override a method, real goal is not to replace the existing behavior but to extend that behavior in some way. Can used super keyword refers to the superclass of the class in which the keyword is used. It is used to refer to the member variables or methods of the superclass.
  • Slide 23
  • Overriding Method public class Employee{ // class name private String name; private double salary; public String getDetail(){ // method declaration return Name : + name \n + Salary : +salary; } public class Manager extends Employee{ // class name private String department; public String getDetail(){ return super.getDetails() +//invoked the entire behavior Manager of : + department; }
  • Slide 24
  • Inheritance and Constructors Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses. You must define a constructor for a class or use the default constructor added by the compiler. The statement super(); calls the superclasss constructor. If the class declaration does not explicitly designate the superclass with the extends clause, then the classs superclass is the Object class.
  • Slide 25
  • Example class definition: class Person { // class name public void sayHello(){ // method declaration System.out.println ( hello guys !); } Is equivalent to class Person { // class name public Person (){ super (); } public void sayHello(){ System.out.println ( hello guys !); } This statement calls the superclasss constructor Automatically added to the classes by compiler Inheritance & Constructor
  • Slide 26
  • Example 2 : constructor definition: class MyClass { // class name private int myInt; public myClass(){ // method declaration myInt = 10; } Compiler will rewrite the constructor to class MyClass { // class name public MyClass (){ Super (); myInt = 10; } Automatically added to the classes by compiler Inheritance & Constructor
  • Slide 27
  • Example 3 : class Vehicle{ // class name private String vin; public Vehicle (String vehicleID){ // constructor declaration vin = vehicleID; } class Truck extends Vehicle{ // class name private int cargoWeightLimit; public Truck (int weightLimit, String vin){ super (vin); cargoWeightLimit = weightLimit; } Notes : If a class has a superclass that is not the Object class, then a constructor of the class should make an explicit call to a constructor of the superclass. Inheritance & Constructor
  • Slide 28
  • Case study Company Payroll Application Commission employee are paid a percentage of their sales Base-salaried commission employee receives a base salary plus percentage of their sales. Commission employee has first name, last name, social security number, commission rate and gross (total) sales amount. Base-salaried commission employee has first name, last name, social security number, commission rate, gross (total) sales amount and base salary
  • Slide 29
  • Polymorphism Polymorphism comes from Greek meaning many forms. Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: Pet myPet; myPet = new Dog();... myPet = new Cat();
  • Slide 30
  • This is another example. If Graduate Student and Undergraduate Student are subclasses of Student, then the following statements are valid: Student student; student = new Student(); student = new GraduateStudent();... student = new UndergraduateStudent();
  • Slide 31
  • Creating the roster Array We can also declare using array. Instead of using two separate array to represent both Graduate and Undergraduate Student, we can declare single array for them. It is because the array elements are objects. We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes. Student roster = new Student[40];... roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent();...
  • Slide 32
  • State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.
  • Slide 33
  • Sample Polymorphic Message To compute the course grade using the roster array, we execute for (int i = 0; i < numberOfStudents; i++) { roster[i].computeCourseGrade(); } If roster[i] refers to a GraduateStudent, then the computeCourseGrade method of the GraduateStudent class is executed. If roster[i] refers to an UndergraduateStudent, then the computeCourseGrade method of the UndergraduateStudent class is executed.
  • Slide 34
  • The instanceof Operator The instanceof operator can help us learn the class of an object. The following code counts the number of undergraduate students. int undergradCount = 0; for (int i = 0; i < numberOfStudents; i++) { if ( roster[i] instanceof UndergraduateStudent ) { undergradCount++; }
  • Slide 35
  • Abstract Superclasses and Abstract Methods When we define a superclass, we often do not need to create any instances of the superclass. Depending on whether we need to create instances of the superclass, we must define the class differently. We will study examples based on the Student superclass defined earlier.
  • Slide 36
  • Definition: Abstract Class An abstract class is a class defined with the modifier abstract OR that contains an abstract method OR that does not provide an implementation of an inherited abstract method that is not intended to be used to create objects. 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. abstract class Student{ abstract public void computeCourseGrades() ; } abstract class Student{ abstract public void computeCourseGrades() ; }
  • Slide 37
  • 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.
  • Slide 38
  • 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.
  • Slide 39
  • 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.
  • Slide 40
  • Inheritance versus Interface The Java interface is used to share common behavior (only method headers) among the instances of different classes.Example : class Person that implements multiple interfaces such as Driver, Commuter and Biker. Inheritance is used to share common code (including both data members and methods) among the instances of related classes. In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code. If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B.