IST311 Advanced Issues in OOP: Inheritance and Polymorphism

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Intro to OOP with Java, C. Thomas Wu
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Abstract Classes Course Lecture Slides 7 June 2010 “None of the abstract.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 11 Inheritance and Polymorphism.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Lecture 4: Object Composition, Inheritance and Polymorphism Michael Hsu CSULA.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved  To develop a subclass from.
1 More About Derived Classes and Inheritance Chapter 9.
Object-Oriented Programming (part 4 – Abstract Classes)
Inheritance.
Chapter 11 Inheritance and Polymorphism
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Inheritance ITI1121 Nour El Kadri.
Lecture 4: Object Composition, Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Ch 10- Advanced Object-Oriented Programming Features
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
IST311 / 602 Cleveland State University – Prof. Victor Matos
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Chapter 9 – Object-Oriented Programming: Inheritance
abstract classes and casting objects
Continuing Chapter 11 Inheritance and Polymorphism
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Chapter 9 Inheritance and Polymorphism
Chapter 14 Abstract Classes and Interfaces
IST311 / 602 Cleveland State University – Prof. Victor Matos
Chapter 11 Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang

Context: Object Oriented Modeling / Programming Entities in the “real world” Programmers Developers Create classes Abstracting the real world

Motivations Suppose you will define classes to model circles, rectangles, and triangles. These geometric classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use object inheritance. 3

Example1: Superclasses & Subclasses

Example1: Superclasses and Subclasses public abstract class GeometricObject { private string color = "White"; private bool filled; private DateTime dateCreated;   // Construct a default GeometricObject protected internal GeometricObject() dateCreated = DateTime.Now; } // create obj with color and filled value protected internal GeometricObject( string colorValue, bool filledValue) Color = colorValue; Filled = filledValue; // Color property public string Color get { return color; } set { this.color = value; } // Filled property: return true if opaque public bool Filled { get { return filled; } set { this.filled = value; } } // DateCreated property public DateTime DateCreated get { return dateCreated; }   // Return a string representing this object public override string ToString() return "\tGeometricObject[" + " created on: " + DateCreated + ", color: " + Color + ", filled: " + Filled + " ] "; // Abstract method Area public abstract double Area(); // Abstract method Perimeter public abstract double Perimeter(); }  2 4 1. Abstract class 2. protected constructor 3. overloaded constructor 2-args 4. abstract methods 3 5 virtual is a C# idiom used to emphasize that a method is not abstract. Only methods explicitly marked as either: virtual or abstract can be overridden!

Example1: Superclasses and Subclasses public class Circle : GeometricObject { private double radius = 1; public Circle() { } public Circle(double radiusValue) : base() Radius = radiusValue; } public Circle(double radiusValue, string colorValue, bool filledValue) : base(colorValue, filledValue) //Color = colorValue; //Filled = filledValue; // Radius property public double Radius get { return radius; } set { this.radius = value;} // calculate Area public override double Area() { return radius * radius * Math.PI; } // calculate Diameter public double Diameter() { return 2 * radius; } // calculate Perimeter public override double Perimeter() { return 2 * radius * Math.PI; }   /* Print Circle info */ public void PrintCircle() { Console.WriteLine(ToString() + " Circle created on: " + DateCreated + " and the radius is " + Radius); } public override string ToString() return "Circle [" + Color + " Radius: " + Radius + " Perimeter: " + String.Format("{0:F2}",Perimeter()) + " Area: " + String.Format("{0:F2}", Area() ) + " ]" + "\n" + base.ToString(); 5 2 4 3 3B

Example1: Superclasses and Subclasses public class Rectangle : GeometricObject { private double width; private double height;   public Rectangle() { } public Rectangle(double widthValue, double heightValue) : base() Width = widthValue; Height = heightValue; } double heightValue, string colorValue, bool filledValue) : base(colorValue, filledValue) // setColor(colorValue); // setFilled(filledValue); public double Width get { return width; } set { this.width = value; } public double Height { get { return height; } set { this.height = value;} }   //calculate Area public override double Area() return Width * Height; // calculate perimeter public override double Perimeter() return 2 * (Width + Height); public override string ToString() return "Rectangle [ Width: " + Width + ", Height: " + Height + ", Perimeter: " + String.Format("{0:F2}", Perimeter() ) + ", Area: " + String.Format("{0:F2}", Area()) + " ]" + "\n" + base.ToString(); 5 2 4 3 3

Example1: Superclasses and Subclasses Testing GeometricObject1, Circle4 and Rectangle1 Classes static void Main(string[] args) { //GeometricObject g = new GeometricObject(); //TRY - Error! Circle c1 = new Circle(); Console.WriteLine(c1); Circle c2 = new Circle(2, "Red", true); Console.WriteLine( c2 ); Rectangle r1 = new Rectangle(1, 2, "Blue", true); Console.WriteLine( r1 ); Console.ReadLine(); } Console Circle [White Radius: 1 Perimeter: 6.28 Area: 3.14 ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: White, filled: False] Circle [Red Radius: 2 Perimeter: 12.57 Area: 12.57 ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: Red, filled: True] Rectangle [ Width: 1, Height: 2, Perimeter: 6.00, Area: 2.00 ] GeometricObjct[created: 4/11/2016 8:21:07 PM, color: Blue, filled: True] 8

Invoking Superclass Constructors Constructors could be invoked explicitly or implicitly. Explicit calls use the base keyword : base () : base (arg1, arg2, …) In implicit calls (the keyword base is not used), the superclass no-arg constructor is automatically invoked. If used, the statement :base() or :base(arguments) must appear in the first line of the subclass constructor. 9

Superclass’s Constructor Is Always Invoked A constructor may invoke a local overloaded constructor or its superclass’s constructor(s). If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, 10

Using the Keyword base The keyword base refers to the superclass of the class in which base appears. base keyword can be used in two ways: Super-class To call a superclass constructor To call a superclass method base. this. Sub-class 11

Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override methods of the superclass Super-class Sub-class 12

Calling Superclass Methods You could invoke an ancestor’s method as follow // Override ancestor’s ToString method public override string ToString() { return "Circle [" + Color + " Radius: " + Radius + " Perimeter: " + String.Format("{0:F2}",Perimeter() ) + " Area: " + String.Format("{0:F2}", Area() ) + " ]" + "\n" + base.ToString(); } 1

NOTE An instance method can be overridden only if it is accessible. A private method cannot be overridden by a subclass because it is not accessible outside its own class. A static method cannot be overridden. 14

The Object Class and Its Methods Object obj; 15

The ToString() method in Object ToString() method returns a string representation of the object. The default implementation returns a string holding: Namespace. A class name of which the object is an instance, Loan boatLoan = new Loan(); Console.WriteLine ( boatLoan.ToString() ); For this example we get something like: MyNameSpace.Loan You should override the ToString method so that it returns a more meaningful string representation of the object. 16

Polymorphism, Dynamic Binding and Generic Programming public static void Main(string[] args) { Show(new GraduateStudent()); Show(new Student()); Show(new Person()); Show(new object()); } // public static void Show (object x) Console.WriteLine(x.ToString()); // ------------------------------------- internal class GraduateStudent : Student public override string ToString() { return "Grad. Student"; } internal class Student : Person { return "Student"; } internal class Person : object { return "Person"; } Polymorphic method Show takes parameters of various types. A method that can be applied to values of different types is called a polymorphic function. In our example which implementation of the ToString() method is used will be determined dynamically by the .NET runtime environment. This capability is known as dynamic binding. Console: Grad. Student Student Person System.Object

Method Matching (Overloading) The compiler finds a matching method according to: parameter type, number of parameters, and order of the parameters at compilation time. Example of different invocation of the pay method bill.PayWith ( 19.99 ) bill.PayWith ("Visa", "1234 1234 1234 1234" ); bill.PayWith ("two cows" ); 18

Casting Objects Casting can be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement Show( new Student() ); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to: Object obj = new Student(); // implicit casting Show(obj); The statement Object obj = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. 19

Why Casting Is Necessary? To tell the compiler that an object should be treated as of a particular type you use an explicit casting. In the example below, msg is a block of binary data that could be interpreted in different ways depending on the casting applied on it. Object msg = ChunkOfBinaryData(); Voice v = (Voice) msg; ... Sms s = (Sms) msg; Email e = (Email) msg; Morse m = (Morse) msg; 20

Casting from Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Apple x = (Apple)fruit; Orange y = (Orange)fruit; double d = 123.45; int n = (int) d; Specializing Observation: Assume fruit is a “banana”. Both castings will fail. The numeric example works. 21

The is Operator Use the is operator to test whether an object is an instance of a given class: object myObject = new Circle(); // Some lines of code here . . . // Perform casting if myObject is an instance of Circle if (myObject is Circle) { Console.WriteLine("The circle diameter is " + ((Circle)myObject).Diameter() ); //... } 22

The Equals Method The equals() method compares the contents of two objects object1.Equals( object2 ) The default implementation of the equals method in the Object class is as follows: public bool Equals ( Object otherObject ) { return ( this == otherObject ); } The Equals method could be overridden in our Circle example as: public override bool Equals ( Object otherObject ) { if (otherObject is Circle) { return this.Radius == ((Circle)otherObject).Radius; } else return false;

NOTE The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The Equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. 24

The protected Modifier The protected modifier can be applied on data and methods in a class. A protected data or method in a public class can be accessed by its subclasses. private ⟶ internal (no modifier is used) ⟶ protected ⟶ public Visibility increases 25

Accessibility Summary Modifier on members in a class Accessed from the same class Accessed from the same namespace Accessed from a subclass Accessed from a different namespace public Yes protected No internal private 26

Visibility Modifiers 27

A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass. private ⟶ default (no modifier is used) ⟶ protected ⟶ public Changes of visibility are valid in this direction ⟶ Changes of visibility are invalid in this direction ⟵ 28

sealed Keyword Modifiers (private, public, protected, internal) are used on classes, methods, and class variables. A sealed class is one that cannot be extended by sub-classing. A sealed method cannot be overridden by its subclasses. 29