Lecture Notes Chapter #9_b Inheritance & Polymorphism

Similar documents
Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Inheritance and Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 11 Inheritance and Polymorphism

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 11 Inheritance and Polymorphism

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

CS1150 Principles of Computer Science Objects and Classes

Chapter 11 Inheritance and Polymorphism

CS-202 Introduction to Object Oriented Programming

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

Inheritance (continued) Inheritance

25. Generic Programming

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

We are on the GUI fast track path

CH. 2 OBJECT-ORIENTED PROGRAMMING

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Practice for Chapter 11

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

CS171:Introduction to Computer Science II. Li Xiong

Generics. CSE260, Computer Science B: Honors Stony Brook University

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Chapter 14 Abstract Classes and Interfaces

Making New instances of Classes

Java Object Oriented Design. CSC207 Fall 2014

ITI Introduction to Computing II

Inheritance (Deitel chapter 9)

Inheritance Motivation

ITI Introduction to Computing II

What is Inheritance?

Programming 2. Inheritance & Polymorphism

Chapter 9 - Object-Oriented Programming: Inheritance

Java Classes, Objects, Inheritance, Abstract and Interfaces Recap

EKT472: Object Oriented Programming. Overloading and Overriding Method

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Abstract Classes Interfaces

Computer Science II (20073) Week 1: Review and Inheritance

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Reusing Classes. Hendrik Speleers

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CSA 1019 Imperative and OO Programming

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance and Polymorphism

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Class, Variable, Constructor, Object, Method Questions

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Inheritance. Transitivity

INHERITANCE. Spring 2019

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Java Fundamentals (II)

COMP 250. inheritance (cont.) interfaces abstract classes

Object Oriented Programming. Java-Lecture 11 Polymorphism

Chapter 9 - Object-Oriented Programming: Polymorphism

ITI Introduction to Computing II

Rules and syntax for inheritance. The boring stuff

Chapter 5 Object-Oriented Programming

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Chapter 13 Abstract Classes and Interfaces

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

ITI Introduction to Computing II

Inheritance and Polymorphism

Java: introduction to object-oriented features

ITI Introduction to Computing II

Questions Answer Key Questions Answer Key Questions Answer Key

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

index.pdf January 21,

Example: Count of Points

CLASS DESIGN. Objectives MODULE 4

Object Orientated Programming Details COMP360

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Introduction to Inheritance

C12a: The Object Superclass and Selected Methods

More Relationships Between Classes

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Classes and Inheritance Extending Classes, Chapter 5.2

1 Shyam sir JAVA Notes

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Inheritance -- Introduction

Final Examination Semester 3 / Year 2010

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Advanced Placement Computer Science. Inheritance and Polymorphism

Exercise: Singleton 1

Part 11 Object Oriented Programming: Inheritance

Chapter 6 Introduction to Defining Classes

Transcription:

Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1 -color: String (object) -fllled: boolean (color) -datecreated: java.util.date +GeometricObject( ) +getcolor( ): String +setcolor(color: String ): void +isfilled( ): boolean +setfilled(filled: boolean): void +getdatecreated( ): java.util.date +tostring( ): String Subclasses derived from extended from Superclass ` Superclass Parent Class Base Class Subclass Child Class Derived Class Extended Class -radius: double Circle4 +Circle( ) +Circle(radius: double) +getradius( ): double +setradius(radius: double): void +getarea( ): double +getparimeter( ): double +getdiameter( ): double +printcircle( ): void -width: double -height: double Rectangle1 +Rectangle( ) +Rectangle(width: double, height: double) +getwidth( ): double +setwidth(width: double): void +getheight( ): double +setheight(height: double): void +getarea( ): double +getperimeter( ): double A child class inherits all accessible data fields and methods from its parent class! A child class does not inherit the constructors of the parent class! The child class may also add uniquely new data fields and methods!

1. Implementation a. GeometricObject1.java public class GeometricObject1 private String color = white ; private boolean filled; private java.util.date datecreated; public GeometricObject1( ) datecreated = new java.util.date( ); public String getcolor( ) return color; public void setcolor(string color) this.color = color; public boolean isfilled( ) return filled; public void setfilled(boolean filled) this.filled = filled; public java.util.date getdatecreated( ) return datecreated; public String tostring( ) return created on + datecreated + \ncolor: + color + and filled: + filled; b. Circle4.java public class Circle4 extends GeometricObject1 private double radius; public Circle4( ) public Circle4(double radius ) this.radius = radius; public double getradius( ) return radius; public void setradius( double radius) this.radius = radius; public double getarea( ) return radius * radius * Math.PI; public double getdiameter( ) return 2 * radius; public double getperimeter( ) return 2 * radius * Math.PI; public void printcircle( ) System.out.println( The circle is created + getdatecreated( ) + and the radius is + radius);

c. Rectangle1.java public class Retangle1 extends GeometricObject1 private double width; private double height; public Rectangle1( ) public Rectangle1(double width, double height ) this width = width; this height = height; public double getwidth( ) return width; public void setwidth(double width) this width = width; public double getheight( ) return height; public void setheigth(double height) this height = height; public double getarea( ) return width * height: public double getperimeter( ) return 2 * (width + height); d. TestCircleRectangle.java public class TestCircleRetangle public static void main(string[ ] args) Circle4 circle = new Circle4(1); System.out.println( circle.tostring( )); System.out.println( circle.getradius( )); System.out.println(circle.getArea( ) ); System.out.println( circle.getdiameter( )); See Liang page 334 for output of TestCircleRectangle.java Rectangle1 rectangle = new Rectangle1(2,4); System.out.println( rectangle.tostring( )); System.out.println(rectangle.getArea( ) ); System.out.println( rectangle.getperimeter( ));

Remark: A subclass is NOT a subset of its superclass; in fact, since the subclass has access to more items than the superclass, an instance of the superclass can be thought of as a subset of an instance of the subclass! Remark: Inheritance is used to model is-a relationships; e.g., an apple is a fruit! For a class B to extend a class A, class B should contain more detailed information than class A. A subclass and a superclass must have an is-a relationship Remark: C++ allows inheritance from multiple classes; i.e., it supports multiple inheritance. Remark: Java does not allow inheritance from multiple classes; a Java class may inherit directly only from one superclass, i.e., the restriction is known as single inheritance. If the extends keyword is used to define a subclass, it allows only one parent class. Multiple inheritance in java is achieved by the use of interfaces. 2. Constructor Chaining A child class inherits all accessible data fields and methods from its parent class, BUT the child class does not inherit the constructors of the parent class! this keyword refers to the calling object self-referential super keyword refers to the parent of the calling object used to o call a superclass constructor super( ) invokes the no-arg constructor of its superclass super(argument list) invokes the superclass constructor that matches the argument list the call for a superclass constructor must be the first statement in the subclass constructor invoking a superclass constructor name in a subclass causes a syntax error if a subclass does not explicitly invoke its superclass constructor, the compiler places the super( ) statement as the first line in the subclass constructor, i.e., public A( ) public A( ) super( );

keyword public class Faculty extends Employee public static void main(string[ ] args) new Faculty( ); Key Constructor Calls Constructor Returns public Faculty( ) System.out.println( (4) Faculty no-arg constructor invoked ); class Employee extends Person public Employee( ) this( (2) Employee s overloaded constructor invoked ); System.out.println( (3) Employee s no-arg constructor invoked ); public Employee( String s ) System.out.println(s); class Person public Person( ) System.out.println( (1) Person s no-arg constructor invoked ); Construction of the Faculty Object Faculty Constructor (4) Employee Constructor (3) Employee Constructor (2) Person Constructor (1) The Parent Constructor is always invoked before the Child Constructor The object is built like a layer cake from the bottom-up

public class Apple extends Fruit class Fruit public Fruit(String name) System.out.println(Fruit constructor is invoked ); Best Practices public Apple( ) PROVIDE EVERY CLASS WITH A NO-ARG CONSTRUCTOR SUCH A POLICY AIDS THE EXTENSION OF THE CLASS, I.E., IT AVOIDS THE ERROR DELINEATED ABOVE Since the Apple class does not have any constructors, a noarg constructor is implicitly declared. The Apple no-arg constructor automatically invokes the Fruit no-arg constructor; but Fruit does not have a no-arg constructor. But since Fruit has an explicitly declared constructor with a parameter, i.e., public Fruit(String name), then the complier cannot implicitly invoke a no-arg constructor. Hence, an Apple object cannot be created and the program cannot be compiled!

3. Overriding Methods super keyword is also used to call a superclass method subclasses inherit methods from their superclasses a subclass may modify the definition of an inherited method for use in that subclass method overriding public class GeometricObject1 private String color = white ; private boolean filled; private java.util.date datecreated; public GeometricObject1( ) datecreated = new java.util.date( ); public String getcolor( ) return color; public void setcolor(string color) this.color = color; public boolean isfilled( ) return filled; public void setfilled(boolean filled) this.filled = filled; public java.util.date getdatecreated( ) return datecreated; public String tostring( ) return created on + datecreated + \ncolor: + color + and filled: + filled; public class Circle4 extends GeometricObject1 private double radius; public Circle4( ) public Circle4(double radius ) this.radius = radius; public double getradius( ) return radius; public void setradius( double radius) this.radius = radius; public double getarea( ) return radius * radius * Math.PI; public double getdiameter( ) return 2 * radius; public double getperimeter( ) return 2 * radius * Math.PI; public void printcircle( ) System.out.println( The circle is created + getdatecreated( ) + and the radius is + radius); public String tostring( ) return super.tostring( ) + \nradius is + radius; The Circle4 tostring( ) method overrides the GeometricObject1 tostring( ) method ; it invokes the GeometricObject1 tostring( ) method and then modifies it to specify information specific to the circle4 object.

a. Rules for Overridding Inherited Methods private data fields in a superclass are not accessible outside of that class, hence they cannot be used directly by a subclass; they can be accessed &/or mutated by public accessor &/or mutators defined in the superclass an instance method can be overridden only if it is accessible; private methods cannot be overridden if a method defined in a subclass is private in its superclass, the two methods are completely unrelated a static method can be inherited, but a static method cannot be overridden remember that static methods are class methods if a static method defined in a superclass is redefined in a subclass, the method defined in the superclass is hidden; the hidden static method can be invoked by using the syntax SuperClassName.staticMethodName( ); b. Overriding versus Overloading i. Overloading same name, different signitures ii. Overriding method defined in the superclass, overridden in a subclass using the same name, same signature, and same return type as defined in the superclass public class Test public static void main(string [ ] args) A a = new A( ); a.p(10); a.p(10) invokes class A method; hence prints 10 class B public void p(int i) class A extends B public void p(int i) System.out.println(i); overrides public class Test public static void main(string [ ] args) A a = new A( ); a.p(10); a.p(10) invokes class B method; hence prints nothing class B public void p(int i) overloads class A extends B public void p(double i) System.out.println(i);

4. Object Class & Methods Every class in Java is descended from java.lang.object If no inheritance is declared when a class is defined, the class is a subclass of Object by default public String tostring( ); returns a string consisting of the objects name, the @ sign, and the objects memory address in hexadecimal, e.g., student@b7f9a1 o Override the tostring( ) method to produce relevant information concerning the subclass objects o System.out.println(student); System.out.println(student.toString( )); public boolean equals(object obj) return (this == obj); default implementation tests whether two reference variables point to the same object Invoked by the statement object1.equals(object2); o Override the equals( ) method to test whether two distinct objects have the same content, e.g., public boolean equals(object o) if (o instanceof Circle) return radius == ((Circle)o).radius; else return false; INSTANCEOF OPERATOR o instanceof Circle returns true if o is an instance of Circle Do not use (Circle o) as the argument when overriding the equals( ) method, i.e., do not use the signature public boolean equals( Circle o) see page 355 #10.12 Comparison Operators/Methods o == operator is used to compare primitive data type values o == operator is also used to compare whether two reference variables refer to the same object (where arrays may be considered to be objects) o The modified equals( ) method can be used to determine whether two objects have the same contents o The equals( ) method can be modified to test the contents of all or a selected subset of the data fields in the class

5. Polymorphism, Dynamic & Generic Programming a class defines a type a type defined by a subclass is a subtype a type defined by a superclass is a supertype a variable must be declared to be of a specific type the type of a variable called it s declared type a variable of a reference type can hold a null value or a reference to an object an object is an instance of a class a subclass is a specialization of its superclass every instance of a subclass is an instance of its superclass o every circle is an object an instance of a superclass is not an instance of a subclass o not every object is a circle an instance of a subclass can be passed to a parameter of its superclass, i.e., a Circle object can be passed to a GeometricObject class prarameter polymorphism an object of a subtype can be used whenever its superclass object is required; i.e., a variable of a supertype can refer to a subtype object dynamic binding given an inheritance chain as follows, class C 4 class C 3 class C 2 class C 1 and the object C 1 o = new C 1 ( ); if the object o were to invoke a method, i.e., o.p( ); then the JVM searches for the method p( ) in the classes in the order C 1, C 2, C 3, C 4, java.lang.object once an implementation of p( ) is found, the search stops and that implementation of p( ) is invoked

public class PolymorphismDemo public static void main(string[ ] args) m(new GraduateStudent( )); m(new Student( )); m(new Person( )); m(new Object( )); public static void m(object x) System.out.println(x.toString( )); class GraduateStudent extends Student class Student extends Person public String tostring( ) return Student ; class Person extends Object public String tostring( ) return Person ; The call for the execution of the method m(new GraduateStudent( )); results in a the invocation of the tostring( ) method; the JVM starts a search of the inheritance chain starting with the GraduateStudent class for an implementation of the tostring( ) method. The Student class yields such an implementation which results in the output of the string Student. The call for the execution of the method m(new Student( )); results in the invocation of its tostring( ) method and the output of the second string Student. The call for the execution of the method m(new Person( )); results in the invocation of its tostring( ) method and the output of the string Person. The call for the execution of the method m(new Object( )); results in the invocation of the java.lang.object s tostring( ) method and the output of a string similar to java.lang.object@ad23f5.

A reference variable s declared type determines which method is matched at compile time; i.e., the compiler uses the parameter type, the number & order of parameters to determine the matching method. For a method defined in several subclasses, the JVM dynamically binds the implementation of a method at runtime decided by the actual class of the object referenced by the variable. Recall that polymorphism refers to the use a variable of a supertype to refer to an object of a subtype; the implementation is known as generic programming. If a methods parameter type is a superclass, then an object of any of the subclasses may be passed to the method via that parameter type. 6. Casting Objects & the instanceof Operator a. Implicit Casting Object o = new Student( ); equivalent m( new Student( )); m( o ); statements An instance of Student is automatically an instance of Object b. Explicit Casting Student b = o; compilation error! An instance of Object is not necessarily an instance of Student Student b = (Student) o; c. Up Casting Casting an instance of a subclass to a variable of a superclass is always possible; implicit casting may be used. d. Down Casting Casting an instance of a superclass to a variable of a subclass: must use explicit casting & object cast must be an instance of the subclass error message ClassCastException e. instanceof Operator Object o = new Circle( ); if( o instanceof Circle ) double d = ((Circle) o ).getdiameter( )); The declared type determines which method to match at compile time;

o.getdiameter( ); would cause a compile error since Object does not contain a getdiameter( ) method. To enable Generic Programming, declare variables with their supertype; thus they can accept a value of any type.

f. TestPolymorphismCasting.java public class TestPolymorphismCasting public static void main(string [ ] args) Object o1 = new Circle4( 1 ); Object o2 = new Rectangle1(1, 1); displayobject(o1); displayobject(o2); public static void displayobject(object o) if (o instanceof Circle4) System.out.println(((Circle4) o ).getarea( )); System.out.println(((Circle4) o ).getdiameter( )); else if (o instanceof Rectangle1) System.out.println(((Rectangle1) o ).getarea( )); Generic Programming 7. ArrayList Class JDK 1.2 Java.util.ArrayList +ArrayList( ) +add(o:object): void +add(index: int, o: Object): void +clear( ): void +contains(o: Object): boolean +get(index: int): Object +indexof(o: Object): int +isempty( ): boolean +lastindexof(o: Object): int +remove(o: Object): boolean +remove(index: int): boolean +size( ): int +set(index: int, o: Object): Object See Liang page 347-348 for program using ArrayList list of differences & similarities between ArrayList operations and Array operations Arrays are fixed in size at creation ArrayLists are extensible at any time 8. Vector Class JDK 1.1 Similar to Arraylist; it is used to store objects. Deprecated by Arraylist in JDK 1.2

9. Composition Construction a. Inheritance models is-a relationships b. Composition models has-a relationships public class MyStack private java.util.arraylist list = new java.util.arraylist( ); public boolean isempty( ) return list.isempty( ); public int getsize( ) return list.size( ); public Object peek( ) return list.get(getsize( ) 1); -- list: ArrayList MyStack + isempty( ): boolean +getsize( ): int +peek( ): Object + pop( ): Object + push(o: Object): Object +search(o: Object): int public Object pop( ) Object o = list.get(getsize( ) 1); list.remove(getsize( ) - 1); return o; public Object push( Object o ) list.add( o ); return o; public int Search( Object o ) return list.lastindexof(o); Returns the index of the first-matching element in the stack by invoking the list.lastindexof( o ) method since the top of the stack is the last element in the list; i.e., the end of the list is the top of the stack. public String tostring( ) Return Stack: + list.tostring( ); The (String)toString method returns a string representation of all of the elements in the ArrayList object

10. protected Data & Methods a. A protected data item or protected method in a public class can be accessed by any class in the same package or by its subclasses even if the subclasses are in different packages. b. Visibility / Accessibility Modifiers Private None Protected Public Modifiers on members in a class Visibility Increases Accessed from the same class Accessed from the same package Accessed from a subclass Accessed from a different package Public Protected None (default) Private Private Modifier Hide members so that they cannot be accessed outside of the class i.e., the members are not intended for use outside of the class Used only for members of the class No Modifier Allow members of the class to be accessed directly from any class within the same package but not from other packages Can be used on the class as well as the members of the class Protected Modifier Enable members to be accessed by the subclasses in any package or classes in the same package, i.e., members of the class are intended for extenders of the class but not for users of the class Used only for members of the class Public Modifier Enable members of the class to be accessed by any class, i.e., members of the class are intended for users of the class Can be used on the class as well as the members of the class A subclass may override a method from a superclass and increase its visibility in the subclass; but it may not restrict the methods visibility, e.g., if a method is defined to be public in the superclass, it cannot be changed to protected, none (default) nor private in the subclass!

Preventing Extending & Overriding public final class C Class C cannot be extended public class Test public final void m( ) Method m( ) cannot be extended