Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.

Similar presentations


Presentation on theme: "Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures."— Presentation transcript:

1 Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures

2 Java Programming: Program Design Including Data Structures2 Chapter Objectives  Learn about inheritance  Learn about subclasses and superclasses  Explore how to override the methods of a superclass  Examine how constructors of superclasses and subclasses work

3 Java Programming: Program Design Including Data Structures3 Chapter Objectives (continued)  Learn about polymorphism  Examine abstract classes  Become aware of interfaces  Learn about composition

4 Java Programming: Program Design Including Data Structures4 Inheritance  “is-a” relationship  Single inheritance:  Subclass is derived from one existing class (superclass)  Multiple inheritance:  Subclass is derived from more than one superclass  Not supported by Java  A class can only extend the definition of one class

5 Java Programming: Program Design Including Data Structures5 Inheritance (continued) modifier(s) class ClassName extends ExistingClassName modifier(s) { memberList }

6 Java Programming: Program Design Including Data Structures6 Inheritance: class Circle Derived from class Shape public class Circle extends Shape {. }

7 Java Programming: Program Design Including Data Structures7 Inheritance (continued) 1.The private members of the superclass are private to the superclass 2.The subclass can directly access the public members of the superclass 3.The subclass can include additional data and method members

8 Java Programming: Program Design Including Data Structures8 Inheritance (continued) 4.The subclass can override (redefine) the public methods of the superclass; applies only to the objects of the subclass, not objects of the superclass 5.All data members of the superclass are also data members of the subclass. Similarly, the methods of the superclass (unless overridden) are also the methods of the subclass

9 Java Programming: Program Design Including Data Structures9 Inheritance (continued)  How to call a method of a superclass from its subclass?  If subclass overrides public method of superclass, use the reserved word super super.MethodName(parameter list)  If subclass does not override public method of superclass, directly call the public method of superclass: MethodName(parameter list)

10 Java Programming: Program Design Including Data Structures10 UML Class Diagram: class Rectangle

11 Java Programming: Program Design Including Data Structures11 class Rectangle public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double l, double w) { setDimension(l, w); } public double getLength() { return length; } public double getWidth() { return width; } public void print() { System.out.print(“Length = “ + length + “; Width = " + width); }

12 Java Programming: Program Design Including Data Structures12 class Rectangle public void setDimension(double l, double w) { if (l >= 0) length = l; else length = 0; if (w >= 0) width = w; else width = 0; } public double area() { return length * width; } public double perimeter() { return 2 * (length + width); }

13 Java Programming: Program Design Including Data Structures13 UML Class Diagram: class Box

14 Java Programming: Program Design Including Data Structures14 class Box public class Box extends Rectangle { private double height; public Box() { super(); height = 0; } public Box(double l, double w, double h) { super(l, w); height = h; } public double getHeight() { return height; } public void print() { super.print(); System.out.print("; Height = " + height); }

15 Java Programming: Program Design Including Data Structures15 class Box public void setDimension(double l, double w, double h) { super.setDimension(l, w); if (h >= 0) height = h; else height = 0; } public double area() { return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height); } public double volume() { return super.area() * height; }

16 Java Programming: Program Design Including Data Structures16 Defining Constructors of the Subclass  Call to constructor of superclass:  Must be first statement  Specified by super parameter list public Box() { super(); height = 0; } public Box(double l, double w, double h) { super(l, w); height = h; }

17 Java Programming: Program Design Including Data Structures17 Objects myRectangle and myBox Rectangle myRectangle = new Rectangle(5, 3); Box myBox = new Box(6, 5, 4);

18 Java Programming: Program Design Including Data Structures18 Protected Members of a Class  The subclass cannot access the private members of the superclass.  If a member of a superclass needs to be accessed in a subclass and still prevent its direct access outside the class,  you must declare that member using the modifier protected.  The accessibility of a protected member of a class falls between public and private.  A subclass can directly access the protected member of a superclass.  In an inheritance hierarchy, the public and protected members of a superclass are directly accessible, in a subclass, across any number of generations, that is, at any level.

19 Java Programming: Program Design Including Data Structures19 Protected Members of a Class

20 Java Programming: Program Design Including Data Structures20 The class Object  In Java, if you define a class and do not use the reserved word extends to derive it from an existing class,  the class you define is automatically considered to be derived from the class Object.  Directly or indirectly becomes the superclass of every class  Public members of class Object can be overridden/invoked by object of any class type

21 Java Programming: Program Design Including Data Structures21 The class Object : Equivalent Definition of a Class public class Clock { //Declare instance variables as given in Chapter 8 //Definition of instance methods as given in Chapter 8 //... } public class Clock extends Object { //Declare instance variables as given in Chapter 8 //Definition of instance methods as given in Chapter 8 //... }

22 Java Programming: Program Design Including Data Structures22 Some Constructors and Methods of the class Object

23 Java Programming: Program Design Including Data Structures23 Constructor  The default constructor is used to initialize an object.  The constructors of the subclass can not directly access and initialize the private instance variables of the superclass.  In order to initialize the inherited instance variables of the superclass, when a subclass object is instantiated, the constructor must automatically execute one of the constructors of the superclass by using the reserved word super.

24 Java Programming: Program Design Including Data Structures24 clone() method  The method clone() makes a copy of the object and returns a reference to the copy.  It makes field by field copy of the object  a memberwise copy, that is a shallow copy of the data, resulting in sharing referenced objects It is always a good idea to override the equals() and toString() method, even if it is not apparent in the design of the class that these methods will be of any use. Both of these methods can be useful while debugging code.

25 Java Programming: Program Design Including Data Structures25 Java Stream Classes  In Java, stream classes are implemented using the inheritance mechanism.  Scanner, FileReader and PrintWriter classes are derived from the class Object.  Refer to Appendix E on CD.

26 Java Programming: Program Design Including Data Structures26 Hierarchy of Java Stream Classes

27 Java Programming: Program Design Including Data Structures27 Polymorphism  We can treat an object of a subclass as an object of its superclass  A reference variable of a superclass type can point to an object of its subclass  useful to develop generic code for a variety of applications Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person("John", "Blair"); employee = new PartTimeEmployee("Susan", "Johnson", 12.50, 45); nameRef = employee; System.out.println("nameRef: " + nameRef); nameRef: Susan Johnson wages are: $562.5

28 Java Programming: Program Design Including Data Structures28 Polymorphism (continued)  The reference variable name or nameRef can point to any object of the class Person, superclass or the class PartTimeEmployee, subclass.  These reference variables have many forms, that is, they are polymorphic reference variables  They can refer to objects of their own class or to objects of the classes inherited from their class

29 Java Programming: Program Design Including Data Structures29 Polymorphism (continued)  In Java, a reference variable of a class can refer to either an object of its own class or an object of its subclass.  Therefore, a reference variable can invoke a method of its own class or of its subclass(es).  Binding means associating a method definition with its invocation.  A method definition is associated with its invocation when the code is compiled (early binding) or at execution time (late binding, dynamic binding, or run-time binding)  Polymorphism: to assign multiple meanings to the same method name  Implemented using late binding

30 Java Programming: Program Design Including Data Structures30 Polymorphism (continued)  Can declare a method of a class final using the keyword final  If a class is declared final,  no other class can be derived from this class. public final void doSomeThing() { //... }  If a method of a class is declared final,  it cannot be overridden with a new definition in a derived class  Java does not use late binding for methods that are private, marked final, or static

31 Polymorphism (continued) Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person(“John, “Blair”); employee = new PartTimeEmployee(“Susan”, “Johnson”, 12.50, 45); nameRef = employee; employeeRef = (PartTimeEmployee) name; // illegal because name points an object of the class Person. employeeRef = (PartTimeEmployee) nameRef; // legal because nareRef refers to the object employee Java Programming: Program Design Including Data Structures31

32 Java Programming: Program Design Including Data Structures32 Polymorphism (continued)  Operator instanceof : determines whether a reference variable that points to an object is of a particular class type  This expression evaluates to true if p points to an object of the class BoxShape ; otherwise it evaluates to false : p instanceof BoxShape

33 Java Programming: Program Design Including Data Structures33 Abstract Methods  A method that has only the heading with no body  Must be declared abstract public void abstract print(); public abstract object larger(object, object); void abstract insert(int insertItem);

34 Java Programming: Program Design Including Data Structures34 Abstract Classes  A class that is declared with the reserved word abstract in its heading  Abstract classes are used as superclasses from which other subclasses within the same context can be derived.  An abstract class can contain instance variables, constructors, finalizers, and non-abstract methods  An abstract class can contain abstract methods  If a class contains an abstract method, the class must be declared abstract

35 Java Programming: Program Design Including Data Structures35 Abstract Classes (continued)  You cannot instantiate an object of an abstract class type; can only declare a reference variable of an abstract class type  You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass

36 Java Programming: Program Design Including Data Structures36 Abstract Class Example public abstract class AbstractClassExample { protected int x; public void abstract print(); public void setX(int a) { x = a; } public AbstractClassExample() { x = 0; }

37 Java Programming: Program Design Including Data Structures37 Interfaces  A class that contains only abstract methods and/or named constants  How Java implements multiple inheritance  To be able to handle a variety of events, Java allows a class to implement more than one interface

38 Java Programming: Program Design Including Data Structures38 Some Interface Definitions public interface WindowListener { public void windowOpened(WindowEvent e); public void windowClosing(WindowEvent e); public void windowClosed(WindowEvent e); public void windowIconified(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowActivated(WindowEvent e); public void windowDeactivated(WindowEvent e); } public interface ActionListener { public void actionPerformed(ActionEvent e); }

39 Java Programming: Program Design Including Data Structures39 Composition  Another way to relate two classes  One or more members of a class are objects of another class type  “has-a” relation between classes  For example, “every person has a date of birth”

40 Java Programming: Program Design Including Data Structures40 Composition Example

41 Java Programming: Program Design Including Data Structures41 Composition Example (continued)

42 Java Programming: Program Design Including Data Structures42 Programming Example: Grade Report  Components: Student, course  Operations on course:  Set course information  Print course information  Show credit hours  Show course number

43 Java Programming: Program Design Including Data Structures43 Components Course and Student

44 Java Programming: Program Design Including Data Structures44 Components Course and Student (continued)

45 Java Programming: Program Design Including Data Structures45 Programming Example: Grade Report  Operations on student:  Set student information  Print student information  Calculate number of credit hours taken  Calculate GPA  Calculate billing amount  Sort the courses according to the course number

46 Java Programming: Program Design Including Data Structures46 Programming Example: Grade Report (continued)  Main algorithm:  Declare variables  Open input file  Open output file  Get number of students registered and tuition rate  Load students’ data  Print grade reports

47 Java Programming: Program Design Including Data Structures47 Sample Output: Grade Report Program

48 Java Programming: Program Design Including Data Structures48 Sample Output: After Clicking Next in Grade Report Program

49 Java Programming: Program Design Including Data Structures49 Chapter Summary  Inheritance:  Single and multiple  Rules  Uses  Superclasses/subclasses (objects)  Overriding/overloading methods  Constructors  The class Object

50 Java Programming: Program Design Including Data Structures50 Chapter Summary (continued)  Java stream classes  Polymorphism  Abstract methods  Abstract classes  Interfaces  Composition


Download ppt "Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures."

Similar presentations


Ads by Google