COS240Lec35_CS InheritancePolymorphism.ppt
Download
Report
Transcript COS240Lec35_CS InheritancePolymorphism.ppt
COS240 O-O Languages
AUBG, COS dept
Lecture 35
Title:
C# vs. Java
Inheritance & Polymorphism
Reference: COS240 Syllabus
8/4/2016
Assoc. Prof. Stoyan Bonev
1
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
8/4/2016
Assoc. Prof. Stoyan Bonev
2
Part 1
INHERITANCE
C#
Programming:
From
Problem
Analysis
to Program
C# Programming:
From
Problem
Analysis
to Program
DesignDesign
3
3
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
4
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
5
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 details
public override string ToString()
{
// return string value
}
• Keyword override added to provide new
implementation details
C# Programming: From Problem Analysis to Program Design
6
Prelude to Inheritance
• File TESTobjectMETHODS.cs
• Run object class methods
– ToString( )
– GetType( )
– GetHashCode( )
• In different contexts
8/4/2016
Assoc. Prof. Stoyan Bonev
7
Context 1
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
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());
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
8
}
Context 2 no user method ToString
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());
}8/4/2016
}
Assoc. Prof. Stoyan Bonev
9
Context 2 no user method ToString
class 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());
}8/4/2016
}
Assoc. Prof. Stoyan Bonev
10
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());
}8/4/2016
}
Assoc. Prof. Stoyan Bonev
11
Context 4 – user method toString qualified override
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());
8/4/2016
}
}
Assoc. Prof. Stoyan Bonev
12
11
Advanced OOP
Features after BDoyle
Inheritance in C#
C# Programming: From Problem Analysis to Program Design
3rd Edition
C# Programming: From Problem Analysis to Program Design
13
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
14
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
15
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)
Derived
class
Base
class
Figure 11-3 Derived class
C# Programming: From Problem Analysis to Program Design
16
Creating Base Classes for
Inheritance
• .
C# Programming: From Problem Analysis to Program Design
17
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
C# Programming: From Problem Analysis to Program Design
18
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
Data
members
19
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
Creating Base Classes for
Inheritance
Continued
// Constructor with zero arguments
definition for
public Person( )
Person class
{
}
// Constructor with four arguments
public Person (string id, string lname, string fname, int anAge)
{
Notice, constructor is a
idNumber = id;
method, has same name
lastName = lname;
as class (Person), has no
firstName = fname;
return type, and is
age = anAge;
overloaded
}
C# Programming: From Problem Analysis to Program Design
21
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
{
Private data
get
member
{
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
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
24
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
25
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
26
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
27
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
28
Creating Derived Classes
• Base class follows the colon
• Derived classes appear to the left of the colon.
public class Student
{
…
}
C# Programming: From Problem Analysis to Program Design
:
Person
29
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
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(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
31
Superclass’s Constructor Is Always Invoked
Next slide explanation
of
HIGH IMPORTANCE!!!
C# Programming: From Problem Analysis to Program Design
32
32
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
33
33
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
34
34
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
35
Relationship
between the
Person and
Student
Classes
Figure 11-5 Inheritance class diagram
C# Programming: From Problem Analysis to Program Design
36
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
37
Person Student inheritance relation
public 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
38
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
39
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
C# Programming: From Problem Analysis to Program Design
40
.
Formal transition from
Inheritance in Java context
To
Inheritance in C# context
Source:Lec Java Inheritance
8/4/2016
Assoc. Prof. Stoyan Bonev
41
Superclass
Subclass
public class Person{
private String name;
public class Student extends Person
{
private int studentNumber;
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;
}
public Student() {
super(); // superclass
studentNumber = 0;
}
public Student(String
initialName,
int initialStudentNumber) {
super(initialName);
studentNumber =
initialStudentNumber;
}
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int
newStudentNumber ) {
studentNumber =
newStudentNumber;
}
42
Superclasses and Subclasses
Geometric
objects: circles and rectangles
Common properties:
– Color, filled/nofilled, dateCreated
Circle
– specific properties:
– radius
Rectangle
– specific properties:
– width, height
8/4/2016
Assoc. Prof. Stoyan Bonev
43
Superclasses and Subclasses
GeometricObject
-color: String
The color of the object (default: white).
-filled: boolean
Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date
The date when the object was created.
+GeometricObject()
Creates a GeometricObject.
+GeometricObject(color: String,
filled: boolean)
Creates a GeometricObject with the specified color and filled
values.
+getColor(): String
Returns the color.
+setColor(color: String): void
Sets a new color.
+isFilled(): boolean
Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
Returns the dateCreated.
+toString(): String
Returns a string representation of this object.
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle(width: double, height: double)
+getRadius(): double
+Rectangle(width: double, height: double
color: String, filled: boolean)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
+getPerimeter(): double
8/4/2016
Assoc. Prof. Stoyan Bonev
44
Superclasses and Subclasses
From
Java to C#
Sub
folder: \Inheritance Demo Programs
Java
program: ProgGeometricObject.java
C#
program: ProgGeometricObject.cs
8/4/2016
Assoc. Prof. Stoyan Bonev
45
Formal transition from Java to C#
Replace
The
import <package>; directive
to
The
8/4/2016
using <namespace>; directive
Assoc. Prof. Stoyan Bonev
46
Formal transition from Java to C#
Replace
Statement
package <name>;
to
Statement
8/4/2016
namespace <name>
{
…
}
Assoc. Prof. Stoyan Bonev
47
Formal transition from Java to C#
Replace
The
camel notation naming convention
to
The
Pascal notation naming convention
E.g. toString() >> ToString()
8/4/2016
Assoc. Prof. Stoyan Bonev
48
Formal transition from Java to C#
Replace
Compound statement end of line style
…
}
….{
to
Compound statement new line style
…
{
…
}
8/4/2016
Assoc. Prof. Stoyan Bonev
49
Formal transition from Java to C#
Replace
The
extends reserved word
to
: - colon character
E.g.
class D1 extends Base >>
class D1 : Base
8/4/2016
Assoc. Prof. Stoyan Bonev
50
Formal transition from Java to C#
Replace
The
super reserved word
to
The
base reserved word
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(…)
Take
8/4/2016
Assoc. Prof. Stoyan Bonev
51
Superclasses and Subclasses
From
Java to C#
Sub
folder: \Inheritance Demo Programs
Java
program: ProgGeometricObject.java
C#
program: ProgGeometricObject.cs
8/4/2016
Assoc. Prof. Stoyan Bonev
52
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(…) { … }
…
}
8/4/2016
Assoc. Prof. Stoyan Bonev
53
Superclasses and Subclasses
Inheritance illustrated as skeletal C# source
class GeometricObject
{
…
}
class Circle : GeometricObject
{
…
}
class Rectangle : GeometricObject
{
…
}
public class TestProgram
{
public static void Main(…) { … }
…
}
8/4/2016
Assoc. Prof. Stoyan Bonev
54
class GeometricObject
Inheritance
illustrated as skeletal C# source
See detailed source text
in file
ProgGeometricObject.cs
8/4/2016
Assoc. Prof. Stoyan Bonev
55
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
8/4/2016
Assoc. Prof. Stoyan Bonev
56
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
8/4/2016
Assoc. Prof. Stoyan Bonev
57
Part 2
POLYMORPHISM
In C#
8/4/2016
C# Programming: From Problem Analysis
Assoc. to
Prof.
Program
StoyanDesign
Bonev
58 58
11
Advanced OOP
Features after BDoyle
Polymorphism in C#
C# Programming: From Problem Analysis to Program Design
3rd Edition
8/4/2016
Assoc.
Prof. Stoyan
C# Programming: From Problem Analysis
to Program
Design Bonev
59 59
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
8/4/2016
Assoc. Prof. Stoyan Bonev
60 60
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
8/4/2016
Assoc.
Prof. Stoyan
C# Programming: From Problem Analysis
to Program
Design Bonev
61 61
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
C# Programming: From Problem Analysis to Program Design
62
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
Extract from Java lecture 14 Polymorphism
8/4/2016
Assoc. Prof. Stoyan Bonev
64
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
65
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()
8/4/2016
Assoc. Prof. Stoyan Bonev
66
Consider code in Java
// source text file: ProgBaseDerv1Derv2.java
public static void main(String args[]) {
Object o = new Object();
Base a = new Base();
System.out.println(" " + o.toString());
System.out.println(" " + a.toString()); a.show();
Derived1 b = new Derived1();
b.show();
Derived2 c = new Derived2();
c.show();
System.out.println(" " + b.toString());
System.out.println(" " + c.toString());
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()
8/4/2016
Assoc. Prof. Stoyan Bonev
67
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
68
Dynamic Binding
Dynamic 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
Since o is an instance of C1, o is also an
Object
8/4/2016
instance of C2, C3, …, Cn-1, and Cn
Assoc. Prof. Stoyan Bonev
69
COS240 O-O Languages
AUBG, COS dept
Formal transition from
Polymorphism in Java context
To
Polymorphism in C# context
Source:Lec Java Polymorphism
8/4/2016
Assoc. Prof. Stoyan Bonev
70
COS240 O-O Languages
AUBG, COS dept
Same formal rules as in case
of Inheritance
8/4/2016
Assoc. Prof. Stoyan Bonev
71
Dynamic binding in C#
From
Sub
Java
C#
Java to C#
folder: \Polymorphism Demo Programs
program: ProgBaseDerv1Derv2.java
program: ProgBaseDerv1Derv2.cs
8/4/2016
Assoc. Prof. Stoyan Bonev
72
Dynamic binding in C#
From
Sub
Java
C#
Java to C#
folder: \Polymorphism Demo Programs
program: ProgramCircle3Cylinder3.java
program: ProgramCircle3Cylinder3.cs
8/4/2016
Assoc. Prof. Stoyan Bonev
73
Thank You
for
Your attention!
Look ahead!
Abstract classes
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
76
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
77
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
78
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
79
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
C# Programming: From Problem Analysis to Program Design
80
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 it
public 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
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
C# Programming: From Problem Analysis to Program Design
85
Interfaces
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
87
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
C# Programming: From Problem Analysis to Program Design
88
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
Review PresentationGUIWithAbstractClassAndInterface Example
C# Programming: From Problem Analysis to Program Design
89
Thank You
for
Your attention!