Download presentation
Presentation is loading. Please wait.
Published byKathleen Bailey Modified over 6 years ago
1
Inheritance & Polymorphism Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus 7/19/2018 Assoc. Prof. Stoyan Bonev
2
Assoc. Prof. Stoyan Bonev
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 7/19/2018 Assoc. Prof. Stoyan Bonev
3
Part 1 INHERITANCE C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 3 Source: Longman dictionary 1987 3
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 C# Programming: From Problem Analysis to Program Design 4 Source: Longman dictionary 1987 4
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 C# Programming: From Problem Analysis to Program Design 5 Source: Longman dictionary 1987 5
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 details public override string ToString() { // return string value } Keyword override added to provide new implementation details C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 6 Source: Longman dictionary 1987 6
7
Prelude to Inheritance
File TESTobjectMETHODS.cs Run object class methods ToString( ) GetType( ) GetHashCode( ) In different contexts 7/19/2018 Assoc. Prof. Stoyan Bonev
8
Assoc. Prof. Stoyan Bonev
Context 1 using 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()); } 7/19/2018 Assoc. Prof. Stoyan Bonev
9
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()); } 7/19/2018 Assoc. Prof. Stoyan Bonev
10
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()); } 7/19/2018 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()); } 7/19/2018 Assoc. Prof. Stoyan Bonev
12
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()); } 7/19/2018 Assoc. Prof. Stoyan Bonev
13
Advanced OOP Features after BDoyle Inheritance in C#
11 C# Programming: From Problem Analysis to Program Design 3rd Edition C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 13 Source: Longman dictionary 1987 13
14
Inheritance Enables you to: Associated with an "is a" relationship
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 C# Programming: From Problem Analysis to Program Design 14 Source: Longman dictionary 1987 14
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 C# Programming: From Problem Analysis to Program Design 15 Source: Longman dictionary 1987 15
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 C# Programming: From Problem Analysis to Program Design 16 Source: Longman dictionary 1987 16
17
Creating Base Classes for Inheritance
. C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 17 Source: Longman dictionary 1987 17
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 C# Programming: From Problem Analysis to Program Design
19
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; Data members C# Programming: From Problem Analysis to Program Design
20
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
21
Creating Base Classes for Inheritance
Continued definition for Person class // 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; Notice, constructor is a method, has same name as class (Person), has no return type, and is overloaded C# Programming: From Problem Analysis to Program Design
22
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
23
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 Private data member C# 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 C# Programming: From Problem Analysis to Program Design 24 Source: Longman dictionary 1987 24
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 C# Programming: From Problem Analysis to Program Design 25 Source: Longman dictionary 1987 25
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 C# Programming: From Problem Analysis to Program Design 26 Source: Longman dictionary 1987 26
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 C# Programming: From Problem Analysis to Program Design 27 Source: Longman dictionary 1987 27
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 C# Programming: From Problem Analysis to Program Design 28 Source: Longman dictionary 1987 28
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 C# Programming: From Problem Analysis to Program Design 29 Source: Longman dictionary 1987 29
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 C# Programming: From Problem Analysis to Program Design 30 Source: Longman dictionary 1987 30
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 C# Programming: From Problem Analysis to Program Design 31 Source: Longman dictionary 1987 31
32
Superclass’s Constructor Is Always Invoked
Next slide explanation of high importance C# Programming: From Problem Analysis to Program Design 32
33
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
34
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
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 C# Programming: From Problem Analysis to Program Design 35 Source: Longman dictionary 1987 35
36
Relationship between the Person and Student Classes
Figure 11-5 Inheritance class diagram C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 36 Source: Longman dictionary 1987 36
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 C# Programming: From Problem Analysis to Program Design 37 Source: Longman dictionary 1987 37
38
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 C# Programming: From Problem Analysis to Program Design 38 Source: Longman dictionary 1987 38
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 C# Programming: From Problem Analysis to Program Design 39 Source: Longman dictionary 1987 39
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 C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 40 Source: Longman dictionary 1987 40
41
Formal transition from Inheritance in Java context To
. Formal transition from Inheritance in Java context To Inheritance in C# context Source:Lec Java Inheritance 7/19/2018
42
Superclass Subclass 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(); // 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;
43
Superclasses and Subclasses
Geometric objects: circles and rectangles Common properties: Color, filled/nofilled, dateCreated Circle – specific properties: radius Rectangle – specific properties: width, height 7/19/2018
44
Superclasses and Subclasses
7/19/2018
45
Superclasses and Subclasses
From Java to C# Sub folder: \Inheritance Demo Programs Java program: ProgGeometricObject.java C# program: ProgGeometricObject.cs 7/19/2018
46
Formal transition from Java to C#
Replace The import <package>; directive to The using <namespace>; directive 7/19/2018
47
Formal transition from Java to C#
Replace Statement package <name>; to Statement namespace <name> { … } 7/19/2018
48
Formal transition from Java to C#
Replace The camel notation naming convention to The Pascal notation naming convention E.g. toString() >> ToString() 7/19/2018
49
Formal transition from Java to C#
Replace Compound statement end of line style ….{ … } to Compound statement new line style { 7/19/2018
50
Formal transition from Java to C#
Replace The extends reserved word to : - colon character E.g. class D1 extends Base >> class D1 : Base 7/19/2018
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(…) 7/19/2018
52
Superclasses and Subclasses
From Java to C# Sub folder: \Inheritance Demo Programs Java program: ProgGeometricObject.java C# program: ProgGeometricObject.cs 7/19/2018
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(…) { … } 7/19/2018
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(…) { … } 7/19/2018
55
class GeometricObject
Inheritance illustrated as skeletal C# source See detailed source text in file ProgGeometricObject.cs 7/19/2018
56
ProgGeometricObject.cs 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 7/19/2018
57
ProgGeometricObject.cs 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 7/19/2018
58
Assoc. Prof. Stoyan Bonev
Part 2 POLYMORPHISM In C# 7/19/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 58 Source: Longman dictionary 1987 58
59
Advanced OOP Features after BDoyle Polymorphism in C#
11 C# Programming: From Problem Analysis to Program Design 3rd Edition 7/19/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 59 Source: Longman dictionary 1987 59
60
Assoc. Prof. Stoyan Bonev
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 7/19/2018 Assoc. Prof. Stoyan Bonev 60 Source: Longman dictionary 1987 60
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 7/19/2018 C# Programming: From Problem Analysis to Program Design Assoc. Prof. Stoyan Bonev 61 Source: Longman dictionary 1987 61
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 C# Programming: From Problem Analysis to Program Design
63
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
64
Extract from Java lecture 14 Polymorphism
7/19/2018 Assoc. Prof. Stoyan Bonev
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. 7/19/2018
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() 7/19/2018
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() 7/19/2018
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. 7/19/2018
69
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. 7/19/2018
70
Formal transition from Polymorphism in Java context To
COS240 O-O Languages AUBG, COS dept Formal transition from Polymorphism in Java context To Polymorphism in C# context Source:Lec Java Polymorphism 7/19/2018
71
Same formal rules as in case of Inheritance
COS240 O-O Languages AUBG, COS dept Same formal rules as in case of Inheritance 7/19/2018
72
Dynamic binding in C# From Java to C#
Sub folder: \Polymorphism Demo Programs Java program: ProgBaseDerv1Derv2.java C# program: ProgBaseDerv1Derv2.cs 7/19/2018
73
Dynamic binding in C# From Java to C#
Sub folder: \Polymorphism Demo Programs Java program: ProgramCircle3Cylinder3.java C# program: ProgramCircle3Cylinder3.cs 7/19/2018
74
Thank You for Your attention! Look ahead!
75
Abstract classes
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 C# Programming: From Problem Analysis to Program Design
81
Sealed classes
82
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
83
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
84
Partial classes
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 C# Programming: From Problem Analysis to Program Design
86
Interfaces
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 C# Programming: From Problem Analysis to Program Design
89
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
90
Thank You for Your attention!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.