07/03/22 Assoc. Prof. Stoyan Bonev 1 COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus
Jan 05, 2016
04/20/23 Assoc. Prof. Stoyan Bonev 1
COS240 O-O Languages AUBG, COS dept
Lecture 35Title:
C# vs. Java Inheritance & Polymorphism
Reference: COS240 Syllabus
04/20/23 Assoc. Prof. Stoyan Bonev 2
Lecture Contents:
• Part 1– Inheritance: Four methods inherited from
the object (System.Object) class – Inheritance: from Java to C#
• Part 2– Polymorphism: from Java to C#
• Sample demo programs
C# Programming: From Problem Analysis to Program Design 3C# Programming: From Problem Analysis to Program Design 3
Part 1
INHERITANCE
C# Programming: From Problem Analysis to Program Design 4C# Programming: From Problem Analysis to Program Design 4
Prelude to Inheritance• C# supports hierarchy of classes.• In C#, the very top level class is called object.• In C#, object is an alias for System.Object
in the .NET Framework. Thus, instead of using System.Object to refer to the top level base class, you can use object.
• When you design your user-defined classes, you can use methods inherited from object by calling them or you can override them and give new definitions for one or more methods.
C# Programming: From Problem Analysis to Program Design 5C# Programming: From Problem Analysis to Program Design 5
Four inherited methods• All user-defined classes inherit four methods from
the object /System.Object/ class, that is on the top of hierarchy:
• ToString()
• Equals()
• GetType()
• GetHashCode()
C# Programming: From Problem Analysis to Program Design 6C# Programming: From Problem Analysis to Program Design 6
ToString( ) Method• ToString() method is called automatically by methods
like Write(), WriteLine()• Can also invoke or call ToString() method directly
• Returns a human-readable string
• Can write a new definition for the ToString() method to include useful detailspublic override string ToString()
{
// return string value
}
• Keyword override added to provide new implementation details
04/20/23 Assoc. Prof. Stoyan Bonev 7
Prelude to Inheritance
• File TESTobjectMETHODS.cs
• Run object class methods– ToString( )– GetType( )– GetHashCode( )
• In different contexts
04/20/23 Assoc. Prof. Stoyan Bonev 8
Context 1using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace TestObjectMethods{ class Program { static void Main(string[] args) { object o = new object(); Console.WriteLine(" " + o.ToString()); Console.WriteLine(" " + o.GetType()); Console.WriteLine(" " + o.GetHashCode()); } }}
04/20/23 Assoc. Prof. Stoyan Bonev 9
Context 2 no user method ToStringclass ModernObject{ private int x; public ModernObject() { x = 0; } // two constructors public ModernObject(int par) { x = par; }
//public override string ToString() { return "User Defined Class";}} // end of class ModernObject class Program{ static void Main(string[] args) { ModernObjecat f = new ModernObject(115); Console.WriteLine(" " + f.ToString()); Console.WriteLine(" " + f.GetType()); Console.WriteLine(" " + f.GetHashCode());
object o = new object(); Console.WriteLine(" " + o.ToString()); Console.WriteLine(" " + o.GetType()); Console.WriteLine(" " + o.GetHashCode()); }}
04/20/23 Assoc. Prof. Stoyan Bonev 10
Context 2 no user method ToStringclass ModernObject : object // implicit uncondition inheritance{ private int x; public ModernObject() { x = 0; } // two constructors public ModernObject(int par) { x = par; }
//public override string ToString() { return "User Defined Class";}} // end of class ModernObject class Program{ static void Main(string[] args) { ModernObjecat f = new ModernObject(115); Console.WriteLine(" " + f.ToString()); Console.WriteLine(" " + f.GetType()); Console.WriteLine(" " + f.GetHashCode());
object o = new object(); Console.WriteLine(" " + o.ToString()); Console.WriteLine(" " + o.GetType()); Console.WriteLine(" " + o.GetHashCode()); }}
04/20/23 Assoc. Prof. Stoyan Bonev 11
Context 3 – user method ToString
class ModernObject{ private int x; public ModernObject() { x = 0; } // two constructors public ModernObject(int par) { x = par; }
public string ToString() { return "User Defined Class";}} // end of class ModernObject
class Program{ static void Main(string[] args) { ModernObjecat f = new ModernObject(115); Console.WriteLine(" " + f.ToString()); Console.WriteLine(" " + f.GetType()); Console.WriteLine(" " + f.GetHashCode());
object o = new object(); Console.WriteLine(" " + o.ToString()); Console.WriteLine(" " + o.GetType()); Console.WriteLine(" " + o.GetHashCode()); }}
04/20/23 Assoc. Prof. Stoyan Bonev 12
class ModernObject{ private int x; public ModernObject() { x = 0; } // two constructors public ModernObject(int par) { x = par; }
public override string ToString() { return "User Defined Class";}} // end of class ModernObject
class Program{ static void Main(string[] args) { ModernObjecat f = new ModernObject(115); Console.WriteLine(" " + f.ToString()); Console.WriteLine(" " + f.GetType()); Console.WriteLine(" " + f.GetHashCode());
object o = new object(); Console.WriteLine(" " + o.ToString()); Console.WriteLine(" " + o.GetType()); Console.WriteLine(" " + o.GetHashCode()); }}
Context 4 – user method toString qualified override
C# Programming: From Problem Analysis to Program Design 13C# Programming: From Problem Analysis to Program Design 13
Advanced OOP Features after BDoyle
Inheritance in C#
C# Programming: From Problem Analysis to Program Design 3rd Edition
11
C# Programming: From Problem Analysis to Program Design 14C# Programming: From Problem Analysis to Program Design 14
Inheritance
• Enables you to: – Create a general class and then define specialized
classes that have access to the members of the general class
• Associated with an "is a" relationship– Specialized class “is a” form of the general class
• Classes can also have a "has a" or "uses" relationship, not associated with inheritance– "has a" relationship is associated with containment or
aggregation, or composition /strong aggregation/
C# Programming: From Problem Analysis to Program Design 15C# Programming: From Problem Analysis to Program Design 15
Inheriting from the Object Class
• Every object inherits four methods as long as reference to the System namespace included
Figure 11-2 Methods inherited from an object
C# Programming: From Problem Analysis to Program Design 16C# Programming: From Problem Analysis to Program Design 16
Inheriting from Other .NET FCL Classes
• Add functionality to programs with minimal programming
• Extend System.Windows.Forms.Form class to build GUIs (Button, Label, TextBox, ListBox)
Base class
Derived class
Figure 11-3 Derived class
C# Programming: From Problem Analysis to Program Design 17C# Programming: From Problem Analysis to Program Design 17
Creating Base Classes for Inheritance
• .
C# Programming: From Problem Analysis to Program Design 18
Creating Base Classes for Inheritance
• Can define your own classes from which other classes can inherit
• Base class is called the super or parent class • Base class has
– Data members defined with a private access modifier
– Constructors defined with public access modifiers
– Properties offering public access to data fields
Creating Base Classes for Inheritance
• Might create a generalized class such as person public class Person
{
private string idNumber;
private string lastName;
private string firstName;
private int age;
C# Programming: From Problem Analysis to Program Design 19
Data members
Access Modifiers
• Class members defined with private access are restricted to members of the current class– Data members are defined with private access modifier
• Private access enables class to protect its data and only allow access to the data through its methods or properties
• Constructors use public access modifier– If they are not public, you would not be able to
instantiate objects of the class in other classes– Constructors are methods
• Named the same name as class and has no return type
C# Programming: From Problem Analysis to Program Design 20
C# Programming: From Problem Analysis to Program Design 21
Creating Base Classes for Inheritance
// Constructor with zero arguments
public Person( )
{
}
// Constructor with four arguments
public Person (string id, string lname, string fname, int anAge)
{
idNumber = id;
lastName = lname;
firstName = fname;
age = anAge;
}
Continued definition for Person class
Notice, constructor is a method, has same name as class (Person), has no
return type, and is overloaded
Access Modifiers
• Properties offer public access to data fields– Properties look like data fields, but are implemented as
methods– Properties provide the getters (accessors) and setters
(mutators) for the class• Make properties read-only by NOT defining the “set”
• Properties often named the same name as their associated data member – EXCEPT, property uses Pascal case (starts with capital letter)– LastName → lastName
C# Programming: From Problem Analysis to Program Design 22
Properties
// Property for last name
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
• Properties defined with public access – they provide access to private data
• No need to declare value. It is used, almost like magic…– value refers to the value sent
through an assignment statement
• get, set and value are contextual keywords
C# Programming: From Problem Analysis to Program Design 23
Private data member
C# Programming: From Problem Analysis to Program Design 24C# Programming: From Problem Analysis to Program Design 24
Creating Base Classes for Inheritance• Can define your own classes from which other
classes can inherit • Base class is called the super or parent class • Data members are defined with a private access
modifier • Constructors are defined with public access
modifiers• Properties offer public access to data fields• Adding properties to your solutions enables access
to the private data using the property identifier, as opposed to writing additional methods.
C# Programming: From Problem Analysis to Program Design 25C# Programming: From Problem Analysis to Program Design 25
Overriding Methods
• When you override a method, you Replace the method defined at a higher level with a new definition or new behavior.
• Keyword override included in derived class– E.g. to override object class ToString() method, you
need to write your user ToString() method with override modifier in the heading.
• Base method includes virtual, abstract, or override keyword – Placing virtual in the base method heading allows the
method to be overridden.
C# Programming: From Problem Analysis to Program Design 26C# Programming: From Problem Analysis to Program Design 26
Using the override keyword
• The override keyword allows a method to provide a new implementation of a method inherited from a base class. When you override a method, signature of methods must match. To override a base method, the base method must be defined as virtual, abstract or override.
• The figure shows the signature for the ToString() method that belongs to the object class.
C# Programming: From Problem Analysis to Program Design 27C# Programming: From Problem Analysis to Program Design 27
Overriding Methods
–
• Overriding a method differs from overloading a method
• Overridden methods have exactly the same signature
• Overloaded methods each have a different signature
C# Programming: From Problem Analysis to Program Design 28C# Programming: From Problem Analysis to Program Design 28
Creating Derived Classes• Derived classes inherit characteristics from a base
class– Also called subclasses or child classes– E.g. given base class Person, Any number of classes
can inherit from Person– E.g class Student inherits from class Person– Person is defined using public access modifier
• protected access modifiers– Access only to classes that derived from them– Access to change data in the base class
C# Programming: From Problem Analysis to Program Design 29C# Programming: From Problem Analysis to Program Design 29
Creating Derived Classes• Base class follows the colon• Derived classes appear to the left of the colon.
public class Student : Person
{
…
}
C# Programming: From Problem Analysis to Program Design 30C# Programming: From Problem Analysis to Program Design 30
Calling the Base Constructor• To call the constructor for the base class, add
keyword :base between the constructor heading for the subclass and the opening curly brace
public Student( )
:base() // base constructor with no arguments
{ . . .
• This calls the default constructor for Person
• To send data to the Person constructor, base keyword is followed by list of arguments. See next slide
C# Programming: From Problem Analysis to Program Design 31C# Programming: From Problem Analysis to Program Design 31
Calling the Base Constructor• To call the constructor for the base class, add
keyword :base between the constructor heading for the subclass and the opening curly brace
public Student(string id, string fname, string lname, string maj, int sId)
:base (id, lname, fname) // base constructor arguments
{ . . .
• Base class must have a constructor with matching signature.
C# Programming: From Problem Analysis to Program Design 3232
Superclass’s Constructor Is Always Invoked
Next slide explanation
of
HIGH IMPORTANCE!!!
C# Programming: From Problem Analysis to Program Design 3333
Superclass’s Constructor Is Always Invoked
In any case, constructing an instance of a class invokes the constructors of all the superclasses along the inheritance chain.
When constructing an object of a subclass, the subclass constructor first invokes its superclass constructor before performing its own tasks.
If the superclass is derived from another class, the superclass constructor invokes its parent-class constructor before performing its own tasks.
This process continues until the last constructor along the inheritance hierarchy is called.
C# Programming: From Problem Analysis to Program Design 3434
Superclass’s Constructor Is Always Invoked
The process described on the previous slide is known as
constructor chaining.
Demo programs:
SonFatherGrandFather.cs
SonFatherGrandFather2.cs
C# Programming: From Problem Analysis to Program Design 35C# Programming: From Problem Analysis to Program Design 35
Using Members of the Base Class
• Scope
– Methods defined in subclass take precedence when named the same name as member of a parent class
• Can call an overridden method of the base class
– Use keyword base before the method name
return base.GetSleepAmt( ) // Calls GetSleepAmt( ) in
// parent class
C# Programming: From Problem Analysis to Program Design 36C# Programming: From Problem Analysis to Program Design 36
Relationship between the Person and
Student Classes
Figure 11-5 Inheritance class diagram
C# Programming: From Problem Analysis to Program Design 37C# Programming: From Problem Analysis to Program Design 37
Person Student inheritance relation• Write C# console application to demonstrate the inheritance
relation Person – Student
• Base class Person
• Data fields: idNumr, lastName, firstName, age
• Constructors: no arg, 1-arg, 3-arg, 4-arg
• Properties: for all data fields
• Override the ToString() method from object class (qualified override)
• Own method that can be overridden by classes that derive from class Person (qualified virtual)
C# Programming: From Problem Analysis to Program Design 38C# Programming: From Problem Analysis to Program Design 38
Person Student inheritance relationpublic class Person
{
private string idNumber;
private string lastName;
private string firstName;
private int age;
public Person()
{ idNumber=“”; lastName=“unknown”; firstName=string.Empty; age=0; }
// more constructors
// properties, getters, setters
// overrides method ToString() method from object class
public override string ToString()
{ return fistName + “ “ + lastName; }
// Own virtual method that can be overridden by classes that derive from class Person
public virtual int GetSleepAmt()
{ return 8 ; }
} // end of class Person
C# Programming: From Problem Analysis to Program Design 39C# Programming: From Problem Analysis to Program Design 39
Person Student inheritance relation• Write C# console application to demonstrate the inheritance
relation Person – Student
• Derived class Student
• Data fields: string major, int studentId;
• Constructors: no arg, 5-arg (2 for Student + 3 for Person)
• Properties: for all data fields
• method that overrides GetSleepAmt() method of the Person class (to demonstrate override keyword)
• method that calls the overridden method of the Person class (to demonstrate use of base keyword)
C# Programming: From Problem Analysis to Program Design 40C# Programming: From Problem Analysis to Program Design 40
Person Student inheritance relation public class Student : Person
{
private string major;
private int studentId;
public Student() : base()
{ major = “unknown”; studentId = 0; }
public Student(string id, string fname, string lname, string maj, int sId)
: base(id, lnamme, fname)
{ major = maj; studentId = sid; }
// properties, getters, setters
// overrides method of the Person class
public override int GetSleepAmt()
{ return 6; }
// method that calls the overridden method of the Person class
public int CallOverriddenGetSleepAmt()
{ return base.GetSleepAmt() ; }
} // end of class Student
Assoc. Prof. Stoyan Bonev04/20/23 41
.
Formal transition fromInheritance in Java context
ToInheritance in C# context
Source:Lec Java Inheritance
42
Superclass
public class Person{private String name;
public Person() {name = “no_name_yet”;
}
public Person(String initialName) {this.name =
initialName;}
public String getName() {return name;
}
public void setName(String newName) {
name = newName;}
Subclass
public class Student extends Person {private int studentNumber;
public Student() {super(); // superclassstudentNumber = 0;
}
public Student(String initialName,
int initialStudentNumber) {
super(initialName);studentNumber =
initialStudentNumber;}
public int getStudentNumber() {return studentNumber;
}
public void setStudentNumber(int newStudentNumber ) {
studentNumber = newStudentNumber;
}
Assoc. Prof. Stoyan Bonev04/20/23 43
Superclasses and Subclasses
Geometric objects: circles and rectangles Common properties:
– Color, filled/nofilled, dateCreated Circle – specific properties:
– radius Rectangle – specific properties:
– width, height
Assoc. Prof. Stoyan Bonev04/20/23 44
Superclasses and Subclasses
GeometricObject -color: String
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
+GeometricObject(color: String, filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
The color of the object (default: white).
Indicates whether the object is filled with a color (default: false).
The date when the object was created.
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled values.
Returns the color.
Sets a new color.
Returns the filled property.
Sets a new filled property.
Returns the dateCreated.
Returns a string representation of this object.
Circle -radius: double
+Circle()
+Circle(radius: double)
+Circle(radius: double, color: String, filled: boolean)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+printCircle(): void
Rectangle -width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+Rectangle(width: double, height: double color: String, filled: boolean)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
+getArea(): double
+getPerimeter(): double
Assoc. Prof. Stoyan Bonev04/20/23 45
Superclasses and Subclasses
From Java to C#
Sub folder: \Inheritance Demo Programs
Java program: ProgGeometricObject.java
C# program: ProgGeometricObject.cs
Assoc. Prof. Stoyan Bonev04/20/23 46
Formal transition from Java to C#
Replace The import <package>; directive to The using <namespace>; directive
Assoc. Prof. Stoyan Bonev04/20/23 47
Formal transition from Java to C#
Replace Statement package <name>; to Statement namespace <name>
{
…
}
Assoc. Prof. Stoyan Bonev04/20/23 48
Formal transition from Java to C#
Replace The camel notation naming convention to The Pascal notation naming convention E.g. toString() >> ToString()
Assoc. Prof. Stoyan Bonev04/20/23 49
Formal transition from Java to C#
Replace Compound statement end of line style ….{
…
} to Compound statement new line style
…
{
…
}
Assoc. Prof. Stoyan Bonev04/20/23 50
Formal transition from Java to C#
Replace The extends reserved word to : - colon character E.g. class D1 extends Base >>
class D1 : Base
Assoc. Prof. Stoyan Bonev04/20/23 51
Formal transition from Java to C#
Replace The super reserved word to The base reserved word
Take out super(…) as the first executable stmt within the constructor and move it to the constructor heading to follow the constructor name as the following context :base(…)
Assoc. Prof. Stoyan Bonev04/20/23 52
Superclasses and Subclasses
From Java to C#
Sub folder: \Inheritance Demo Programs
Java program: ProgGeometricObject.java
C# program: ProgGeometricObject.cs
Assoc. Prof. Stoyan Bonev04/20/23 53
Superclasses and Subclasses Inheritance illustrated as skeletal Java source
class GeometricObject {… } class Circle extends GeometricObject {…} class Rectangle extends GeometricObject {…} public class TestProgram {public static void main(…) { … }…
}
Assoc. Prof. Stoyan Bonev04/20/23 54
Superclasses and Subclasses Inheritance illustrated as skeletal C# source
class GeometricObject { … } class Circle : GeometricObject { … } class Rectangle : GeometricObject { … } public class TestProgram {
public static void Main(…) { … }…
}
Assoc. Prof. Stoyan Bonev04/20/23 55
class GeometricObject
Inheritance illustrated as skeletal C# source
See detailed source text in file
ProgGeometricObject.cs
Assoc. Prof. Stoyan Bonev04/20/23 56
Task 1
Write a C# program to illustrate the inheritance relation among classes Circle and Cylinder
Super class: Circle
sub class: Cylinder
“is-a” relation: Cylinder is-a Circle
Hint: Follow the style and ideology of C# program
ProgGeometricObject.cs
Assoc. Prof. Stoyan Bonev04/20/23 57
Task 2
Write a C# program to illustrate the inheritance relation among classes Rectangle and Box/Pool
Super class: Rectangle
sub class: Box
“is-a” relation: Box is-a Rectangle
Hint: Follow the style of C# program
ProgGeometricObject.cs
04/20/23 Assoc. Prof. Stoyan Bonev 58C# Programming: From Problem Analysis to Program Design 58
Part 2
POLYMORPHISMIn C#
04/20/23 Assoc. Prof. Stoyan Bonev 59C# Programming: From Problem Analysis to Program Design 59
Advanced OOP Features after BDoyle
Polymorphism in C#
C# Programming: From Problem Analysis to Program Design 3rd Edition
11
04/20/23 Assoc. Prof. Stoyan Bonev 6060
Polymorphism
• Ability for classes to provide different implementations of methods called by the same name
– ToString( ) method
• Dynamic binding
– Determines which method to call at run time based on which object calls the method
04/20/23 Assoc. Prof. Stoyan Bonev 61C# Programming: From Problem Analysis to Program Design 61
Overriding Methods (continued)
• Example of polymorphism – ToString() method can have many
different definitions – ToString() uses the virtual
modifier, implying that any class can override it
C# Programming: From Problem Analysis to Program Design 62
Polymorphism• Polymorphism is implemented through interfaces, inheritance,
and the use of abstract classes
• Ability for classes to provide different implementations details for methods with same name
– Determines which method to call or invoke at run time based on which object calls the method (Dynamic binding)
– Example…ToString( ) method
• Through inheritance, polymorphism is made possible by allowing classes to override base class members
Polymorphic Programming in .NET (continued)
• Actual details of the body of interface methods are left up to the classes that implement the interface– Method name is the same
– Every class that implements the interface may have a completely different behavior
C# Programming: From Problem Analysis to Program Design 63
04/20/23 Assoc. Prof. Stoyan Bonev 64
Extract from Java lecture 14 Polymorphism
Assoc. Prof. Stoyan Bonev04/20/23 65
Polymorphism
A subclass is a specialized form of its superclass. Every instance of a sub class is an instance of a
superclass BUT not vice versa. Example: Every circle is a geometric object, BUT
not every geometric object is a circle. You can always assign an instance of a subclass to a
reference variable of its superclass type. You can always pass an instance of a subclass as a
parameter/argument of its superclass type.
Assoc. Prof. Stoyan Bonev04/20/23 66
Consider code in Java // source text file: ProgBaseDerv1Derv2.java
given inheritance hierarchy
Object – Base – Derived1, Derived2
Classes Base, Derived1, Derived2 provide methods toString() and show()
Assoc. Prof. Stoyan Bonev04/20/23 67
Consider code in Java // source text file: ProgBaseDerv1Derv2.java
public static void main(String args[]) { Object o = new Object(); System.out.println(" " + o.toString()); Base a = new Base(); System.out.println(" " + a.toString()); a.show(); Derived1 b = new Derived1(); System.out.println(" " + b.toString()); b.show(); Derived2 c = new Derived2(); System.out.println(" " + c.toString()); c.show(); Object[ ] arr = new Object[4]; arr[0] = o; arr[1] = a; arr[2] = b; arr[3] = c; for(int i=0; i<4; i++)System.out.println( arr[i].toString()); // o is named polymorphic variable o=a; o=b; o=c; // allowed assignment a=b; a=c;
} // end of method main()
Assoc. Prof. Stoyan Bonev04/20/23 68
Comments Ref variable o is Object type. Array ref variable arr is Object type. We can assign any instance of Object ((eg. New Base,
new Derived1, or new Derived2 to o or to arr array element
GEN RULE: An object of a subtype can be used wherever its supertype value is required or in other words a ref var of a super class type can point to an object of its sub class type.
This feature is known as polymorphism.
Assoc. Prof. Stoyan Bonev04/20/23 69
Dynamic BindingDynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.
Cn Cn-1 . . . . . C2 C1
Object Since o is an instance of C1, o is also an
instance of C2, C3, …, Cn-1, and Cn
Assoc. Prof. Stoyan Bonev04/20/23 70
COS240 O-O Languages AUBG, COS dept
Formal transition fromPolymorphism in Java context
ToPolymorphism in C# context
Source:Lec Java Polymorphism
Assoc. Prof. Stoyan Bonev04/20/23 71
COS240 O-O Languages AUBG, COS dept
Same formal rules as in case of Inheritance
Assoc. Prof. Stoyan Bonev04/20/23 72
Dynamic binding in C#
From Java to C#
Sub folder: \Polymorphism Demo Programs
Java program: ProgBaseDerv1Derv2.java
C# program: ProgBaseDerv1Derv2.cs
Assoc. Prof. Stoyan Bonev04/20/23 73
Dynamic binding in C#
From Java to C#
Sub folder: \Polymorphism Demo Programs
Java program: ProgramCircle3Cylinder3.java
C# program: ProgramCircle3Cylinder3.cs
Thank Youfor
Your attention!
Look ahead!
Abstract classes
C# Programming: From Problem Analysis to Program Design 76
Abstract Classes• Useful for implementing abstraction
– Identify and pull out common characteristics that all objects of that type possess
• Class created solely for the purpose of inheritance– Provide a common definition of a base class so that
multiple derived classes can share that definition
• For example, Person → Student, Faculty– Person defined as base abstract class
– Student defined as derived subclass
C# Programming: From Problem Analysis to Program Design 77
Abstract Classes• Add keyword abstract on class heading
[access modifier] abstract class ClassIdentifier { } // Base class
• Started new project – used same classes, added abstract to heading of Person base class (PresentationGUIWithAbstractClassAndInterface Example)
public abstract class Person
C# Programming: From Problem Analysis to Program Design 78
Abstract Classes• Abstract classes used to prohibit other classes
from instantiating objects of the class
– Can create subclasses (derived classes) of the abstract class
– Derived classes inherit characteristics from base abstract class
– Objects can only be created using classes derived from the abstract class
C# Programming: From Problem Analysis to Program Design 79
Abstract Methods • Only permitted in abstract classes
• Method has no body
– Implementation details of the method are left up to classes derived from the base abstract class
• Every class that derives from the abstract class must provide implementation details for all abstract methods
– Sign a contract that details how to implement its abstract methods
C# Programming: From Problem Analysis to Program Design 80
Abstract Methods (continued)• No additional special keywords are used when a
new class is defined to inherit from the abstract base class
[access modifier] abstract returnType MethodIdentifier
([parameter list]) ; // No { } included
• Declaration for abstract method ends with semicolon; NO method body or curly braces
• Syntax error if you use the keyword static or virtual when defining an abstract method
Sealed classes
Sealed Classes
• Sealed class cannot be a base class• Sealed classes are defined to prevent derivation• Objects can be instantiated from the class, but
subclasses cannot be derived from itpublic sealed class SealedClassExample
• Number of .NET classes defined with the sealed modifier– Pen and Brushes classes
C# Programming: From Problem Analysis to Program Design 82
Sealed Methods
• If you do not want subclasses to be able to provide new implementation details, add the keyword sealed– Helpful when a method has been defined as virtual in a
base class
– Don’t seal a method unless that method is itself an override of another method in some base class
C# Programming: From Problem Analysis to Program Design 83
Partial classes
C# Programming: From Problem Analysis to Program Design 85
Partial Classes
• Break class up into two or more files– Each file uses partial class designation
• Used by Visual Studio for Windows applications– Code to initialize controls and set properties is placed
in a somewhat hidden file in a region labeled “Windows Form Designer generated code”
– File is created following a naming convention of “FormName.Designer.cs” or “xxx.Designer.cs”
– Second file stores programmer code
• At compile time, the files are merged together
Interfaces
C# Programming: From Problem Analysis to Program Design 87
Interfaces• C# supports single inheritance
– Classes can implement any number of interfaces
– Only inherit from a single class, abstract or nonabstract
• Think of an interface as a class that is totally abstract; all methods are abstract– Abstract classes can have abstract and regular methods
– Classes implementing interface agree to define details for all of the interface’s methods
C# Programming: From Problem Analysis to Program Design 88
Interfaces (continued)• General form
[modifier] interface InterfaceIdentifier
{
// members - no access modifiers are used
}
• Members can be methods, properties, or events
– No implementations details are provided for any of its members
Implement the Interface (continued)
• Heading for the class implementing the interface identifies base class and one or more interfaces following the colon (:) [Base class comes first]
[modifier] class ClassIdentifier : identifier [, identifier]
public class Student : Person, Itraveler
• For testing purposes, PresentationGUI class in the PresentationGUIAbtractClassAndInterface folder modified to include calls to interface methods
C# Programming: From Problem Analysis to Program Design 89Review PresentationGUIWithAbstractClassAndInterface Example
Thank Youfor
Your attention!