Presentation is loading. Please wait.

Presentation is loading. Please wait.

IST311 Advanced Issues in OOP: Inheritance and Polymorphism

Similar presentations


Presentation on theme: "IST311 Advanced Issues in OOP: Inheritance and Polymorphism"— Presentation transcript:

1 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

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

3 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

4 Example1: Superclasses & Subclasses

5 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 protected constructor 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!

6 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

7 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

8 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: Area: ] 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

9 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

10 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

11 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

12 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

13 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

14 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

15 The Object Class and Its Methods
Object obj; 15

16 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

17 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

18 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 ( ) bill.PayWith ("Visa", " " ); bill.PayWith ("two cows" ); 18

19 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

20 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; e = ( ) msg; Morse m = (Morse) msg; 20

21 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 = ; int n = (int) d; Specializing Observation: Assume fruit is a “banana”. Both castings will fail. The numeric example works. 21

22 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

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

24 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

25 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

26 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

27 Visibility Modifiers 27

28 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

29 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


Download ppt "IST311 Advanced Issues in OOP: Inheritance and Polymorphism"

Similar presentations


Ads by Google