1 / 40

Inheritance and Polymorphism

Inheritance and Polymorphism. 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.

odina
Download Presentation

Inheritance and Polymorphism

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. Inheritance and Polymorphism

  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.

  3. Inheritance • Inheritance • Software reusability • Create new class from existing class • Absorb existing class’s data and behaviors • Enhance with new capabilities • Subclass extends superclass • Subclass • More specialized group of objects • Behaviors inherited from superclass • Can customize • Additional behaviors

  4. Inheritance To design two or more entities that are different but share many common features. Steps : • Define a class that contains the common feature of the entities • 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

  5. Examples

  6. Manager Employee +name : String +salary : double +birthDate : Date +department : String +name : String +salary : double +birthDate : Date +getDetails () : String +getDetails () : String Example public class Employee{ public String name; public double salary; public Date birthDate; public void getDetail(){ //... } public class Manager{ public String name; public double salary; public Date birthDate; public String department; public void getDetail(){ //... }

  7. Employee Inheritance Concept 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 +name : String +salary : double +birthDate : Date +getDetails () : String Manager +department : String

  8. Employee 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; } +name : String +salary : double +birthDate : Date +getDetail () : String Manager +department : String <modifier> class <className> extends <superclass> { // <declaration> }

  9. Director Inheritance Tree Employee name : String salary : double birthDate : Date getDetail () : String Manager Engineer +department : String + carAllowance : double + inceaseAllowance()

  10. Another example • Case Study: • Suppose we want 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.

  11. Defining Classes with Inheritance Type of Student Grading System Undergraduate pass if (test1+test2+test3/3) >=70 Graduate pass if (test1+test2+test3/3) >=80 • Steps: • Define two unrelated classes for undergraduate and graduate students • Define entities that share common data or behavior (avoid duplication) • Design these two classes using inheritance • Define 3 classes • Student (class to incorporate behavior and data common to both graduate and undergraduate • GraduateStudents (class to incorporate behavior specific to graduate students) • UndergraduateStudents (class to incorporate behavior specific to undergraduate students)

  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.

  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.

  14. Inheritance Hierarchy

  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.

  16. Instances This shows the inherited components of the superclass are part of the subclass instance Class Hierarchy Inheritance and Member Accessibility • We use the following visual representation of inheritance to illustrate data member accessibility.

  17. The Effect of Three Visibility Modifiers

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

  19. Accessibility from Another Instance • Data members accessible from an instance are also accessible from other instances of the same class.

  20. Accessibility

  21. Overriding Method • A subclass can modify behavior inherited form parent class • A subclass can create a method with different functionality than the parent’s method but with the same: > name > return type > argument list • Overriding is to adding additional features; modify existing behavior.

  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.

  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; } }

  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 superclass’s constructor. • If the class declaration does not explicitly designate the superclass with the extends clause, then the class’s superclass is the Object class.

  25. Inheritance & Constructor 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 superclass’s constructor Automatically added to the classes by compiler

  26. Inheritance & Constructor 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

  27. Inheritance & Constructor 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.

  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

  29. Pet myPet; myPet = new Dog(); . . . myPet = new Cat(); 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:

  30. Student student; student = new Student(); student = new GraduateStudent(); . . . student = new UndergraduateStudent(); • This is another example. • If Graduate Student and Undergraduate Student are subclasses of Student, then the following statements are valid:

  31. Student roster = new Student[40]; . . . roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent(); . . . 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.

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

  33. for(inti = 0; i < numberOfStudents; i++) { roster[i].computeCourseGrade(); } Sample Polymorphic Message • To compute the course grade using the roster array, we execute • 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.

  34. 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 of an object. • The following code counts the number of undergraduate students.

  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.

  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() ;}

  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.

  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.

  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.

  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.

More Related