Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism

Similar presentations


Presentation on theme: "Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism"— Presentation transcript:

1 Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
©The McGraw-Hill Companies, Inc.

2 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

3 Intro to OOP with Java, C. Thomas Wu
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 ©The McGraw-Hill Companies, Inc.

4 Intro to OOP with Java, C. Thomas Wu
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 ©The McGraw-Hill Companies, Inc.

5 Intro to OOP with Java, C. Thomas Wu
Examples ©The McGraw-Hill Companies, Inc.

6 Intro to OOP with Java, C. Thomas Wu
Example public class Employee{ public String name; public double salary; public Date birthDate; public void getDetail(){ //... } 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 ©The McGraw-Hill Companies, Inc.

7 Intro to OOP with Java, C. Thomas Wu
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 Employee +name : String +salary : double +birthDate : Date +getDetails () : String Manager +department : String ©The McGraw-Hill Companies, Inc.

8 Intro to OOP with Java, C. Thomas Wu
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 +name : String +salary : double +birthDate : Date +getDetail () : String Manager +department : String <modifier> class <className> extends <superclass> { // <declaration> } ©The McGraw-Hill Companies, Inc.

9 Intro to OOP with Java, C. Thomas Wu
Inheritance Tree Employee name : String salary : double birthDate : Date getDetail () : String Manager Engineer +department : String Director + carAllowance : double + inceaseAllowance() ©The McGraw-Hill Companies, Inc.

10 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

11 Defining Classes with Inheritance
Intro to OOP with Java, C. Thomas Wu 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) ©The McGraw-Hill Companies, Inc.

12 Modeling Two Types of Students
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

13 Classes for the Class Roster
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

14 Inheritance Hierarchy
Intro to OOP with Java, C. Thomas Wu Inheritance Hierarchy ©The McGraw-Hill Companies, Inc.

15 The Protected Modifier
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

16 Inheritance and Member Accessibility
Intro to OOP with Java, C. Thomas Wu Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. This shows the inherited components of the superclass are part of the subclass instance Instances Class Hierarchy ©The McGraw-Hill Companies, Inc.

17 The Effect of Three Visibility Modifiers
Intro to OOP with Java, C. Thomas Wu The Effect of Three Visibility Modifiers ©The McGraw-Hill Companies, Inc.

18 Accessibility of Super from Sub
Intro to OOP with Java, C. Thomas Wu Accessibility of Super from Sub Everything except the private members of the Super class is visible from a method of the Sub class. ©The McGraw-Hill Companies, Inc.

19 Accessibility from Another Instance
Intro to OOP with Java, C. Thomas Wu Accessibility from Another Instance Data members accessible from an instance are also accessible from other instances of the same class. ©The McGraw-Hill Companies, Inc.

20 Intro to OOP with Java, C. Thomas Wu
Accessibility Modifier Same class Same Package Subclass Universe private Yes default protected public ©The McGraw-Hill Companies, Inc.

21 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

22 Rules About Overriding Method
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

23 Intro to OOP with Java, C. Thomas Wu
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; ©The McGraw-Hill Companies, Inc.

24 Inheritance and Constructors
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

25 Intro to OOP with Java, C. Thomas Wu
Inheritance & Constructor Example class definition: class Person { // class name public void sayHello(){ // method declaration System.out.println (“ hello guys !”); } Is equivalent to public Person (){ super (); public void sayHello(){ This statement calls the superclass’s constructor Automatically added to the classes by compiler ©The McGraw-Hill Companies, Inc.

26 Intro to OOP with Java, C. Thomas Wu
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 public MyClass (){ Super (); Automatically added to the classes by compiler ©The McGraw-Hill Companies, Inc.

27 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

28 Case study – Company Payroll Application
Intro to OOP with Java, C. Thomas Wu 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 ©The McGraw-Hill Companies, Inc.

29 Intro to OOP with Java, C. Thomas Wu
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(); A variable of class X may not refer to an object from the superclass or sibling classes of X. Sibling classes are those that share the common ancestor class. For example, the following statements are invalid: Dog myDog = new Cat(); Cat myCat = new Pet(); ©The McGraw-Hill Companies, Inc.

30 Intro to OOP with Java, C. Thomas Wu
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(); ©The McGraw-Hill Companies, Inc.

31 Creating the roster Array
Intro to OOP with Java, C. Thomas Wu 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(); ©The McGraw-Hill Companies, Inc.

32 State of the roster Array
Intro to OOP with Java, C. Thomas Wu State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. ©The McGraw-Hill Companies, Inc.

33 Sample Polymorphic Message
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

34 The instanceof Operator
Intro to OOP with Java, C. Thomas Wu 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++; } ©The McGraw-Hill Companies, Inc.

35 Abstract Superclasses and Abstract Methods
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

36 Definition: Abstract Class
Intro to OOP with Java, C. Thomas Wu 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() ; } ©The McGraw-Hill Companies, Inc.

37 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

38 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

39 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

40 Inheritance versus Interface
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.


Download ppt "Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism"

Similar presentations


Ads by Google