Presentation is loading. Please wait.

Presentation is loading. Please wait.

11/23/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus.

Similar presentations


Presentation on theme: "11/23/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus."— Presentation transcript:

1 11/23/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus

2 11/23/2015Assoc. Prof. Stoyan Bonev2 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

3 C# Programming: From Problem Analysis to Program Design3 3 Part 1 INHERITANCE

4 C# Programming: From Problem Analysis to Program Design4 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.

5 C# Programming: From Problem Analysis to Program Design5 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()

6 C# Programming: From Problem Analysis to Program Design6 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

7 11/23/2015Assoc. Prof. Stoyan Bonev7 Prelude to Inheritance File TESTobjectMETHODS.cs Run object class methods –ToString( ) –GetType( ) –GetHashCode( ) In different contexts

8 11/23/2015Assoc. Prof. Stoyan Bonev8 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()); }

9 11/23/2015Assoc. Prof. Stoyan Bonev9 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()); }

10 11/23/2015Assoc. Prof. Stoyan Bonev10 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()); }

11 11/23/2015Assoc. Prof. Stoyan Bonev11 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()); }

12 11/23/2015Assoc. Prof. Stoyan Bonev12 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

13 C# Programming: From Problem Analysis to Program Design13C# Programming: From Problem Analysis to Program Design13 Advanced OOP Features after BDoyle Inheritance in C# C# Programming: From Problem Analysis to Program Design 3rd Edition 11

14 C# Programming: From Problem Analysis to Program Design14C# Programming: From Problem Analysis to Program Design14 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/

15 C# Programming: From Problem Analysis to Program Design15C# Programming: From Problem Analysis to Program Design15 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

16 C# Programming: From Problem Analysis to Program Design16C# Programming: From Problem Analysis to Program Design16 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

17 C# Programming: From Problem Analysis to Program Design17C# Programming: From Problem Analysis to Program Design17 Creating Base Classes for Inheritance.

18 C# Programming: From Problem Analysis to Program Design18 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

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; C# Programming: From Problem Analysis to Program Design19 Data members

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 Design20

21 C# Programming: From Problem Analysis to Program Design21 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

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 Design22

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 C# Programming: From Problem Analysis to Program Design23 Private data member

24 C# Programming: From Problem Analysis to Program Design24C# Programming: From Problem Analysis to Program Design24 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.

25 C# Programming: From Problem Analysis to Program Design25C# Programming: From Problem Analysis to Program Design25 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.

26 C# Programming: From Problem Analysis to Program Design26C# Programming: From Problem Analysis to Program Design26 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.

27 C# Programming: From Problem Analysis to Program Design27C# Programming: From Problem Analysis to Program Design27 Overriding Methods – Overriding a method differs from overloading a method Overridden methods have exactly the same signature Overloaded methods each have a different signature

28 C# Programming: From Problem Analysis to Program Design28C# Programming: From Problem Analysis to Program Design28 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

29 C# Programming: From Problem Analysis to Program Design29C# Programming: From Problem Analysis to Program Design29 Creating Derived Classes Base class follows the colon Derived classes appear to the left of the colon. public class Student : Person { … }

30 C# Programming: From Problem Analysis to Program Design30C# Programming: From Problem Analysis to Program Design30 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

31 C# Programming: From Problem Analysis to Program Design31C# Programming: From Problem Analysis to Program Design31 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.

32 C# Programming: From Problem Analysis to Program Design32 Superclass’s Constructor Is Always Invoked Next slide explanation of HIGH IMPORTANCE!!!

33 C# Programming: From Problem Analysis to Program Design33 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.

34 C# Programming: From Problem Analysis to Program Design34 Superclass’s Constructor Is Always Invoked The process described on the previous slide is known as constructor chaining. Demo programs: SonFatherGrandFather.cs SonFatherGrandFather2.cs

35 C# Programming: From Problem Analysis to Program Design35C# Programming: From Problem Analysis to Program Design35 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

36 C# Programming: From Problem Analysis to Program Design36C# Programming: From Problem Analysis to Program Design36 Relationship between the Person and Student Classes Figure 11-5 Inheritance class diagram

37 C# Programming: From Problem Analysis to Program Design37C# Programming: From Problem Analysis to Program Design37 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 )

38 C# Programming: From Problem Analysis to Program Design38C# Programming: From Problem Analysis to Program Design38 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

39 C# Programming: From Problem Analysis to Program Design39C# Programming: From Problem Analysis to Program Design39 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)

40 C# Programming: From Problem Analysis to Program Design40C# Programming: From Problem Analysis to Program Design40 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

41 Assoc. Prof. Stoyan Bonev 11/23/2015 41. Formal transition from Inheritance in Java context To Inheritance in C# context Source:Lec Java Inheritance

42 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(); // 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 Assoc. Prof. Stoyan Bonev 11/23/2015 43 Superclasses and Subclasses F Geometric objects: circles and rectangles F Common properties: –Color, filled/nofilled, dateCreated F Circle – specific properties: –radius F Rectangle – specific properties: –width, height

44 Assoc. Prof. Stoyan Bonev 11/23/2015 44 Superclasses and Subclasses

45 Assoc. Prof. Stoyan Bonev 11/23/2015 45 Superclasses and Subclasses F From Java to C#  Sub folder: \Inheritance Demo Programs  Java program: ProgGeometricObject.java  C# program: ProgGeometricObject.cs

46 Assoc. Prof. Stoyan Bonev 11/23/2015 46 Formal transition from Java to C# F Replace  The import ; directive F to  The using ; directive

47 Assoc. Prof. Stoyan Bonev 11/23/2015 47 Formal transition from Java to C# F Replace  Statement package ; F to  Statement namespace { … }

48 Assoc. Prof. Stoyan Bonev 11/23/2015 48 Formal transition from Java to C# F Replace F The camel notation naming convention F to F The Pascal notation naming convention  E.g. toString() >> ToString()

49 Assoc. Prof. Stoyan Bonev 11/23/2015 49 Formal transition from Java to C# Replace  Compound statement end of line style ….{ … } F to F Compound statement new line style … { … }

50 Assoc. Prof. Stoyan Bonev 11/23/2015 50 Formal transition from Java to C# F Replace  The extends reserved word F to  : - colon character  E.g. class D1 extends Base >> class D1 : Base

51 Assoc. Prof. Stoyan Bonev 11/23/2015 51 Formal transition from Java to C# F Replace  The super reserved word F 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(…)

52 Assoc. Prof. Stoyan Bonev 11/23/2015 52 Superclasses and Subclasses F From Java to C#  Sub folder: \Inheritance Demo Programs  Java program: ProgGeometricObject.java  C# program: ProgGeometricObject.cs

53 Assoc. Prof. Stoyan Bonev 11/23/2015 53 Superclasses and Subclasses F Inheritance illustrated as skeletal Java source class GeometricObject { … } class Circle extends GeometricObject { … } class Rectangle extends GeometricObject { … } public class TestProgram { public static void main(…) { … } … }

54 Assoc. Prof. Stoyan Bonev 11/23/2015 54 Superclasses and Subclasses F Inheritance illustrated as skeletal C# source class GeometricObject { … } class Circle : GeometricObject { … } class Rectangle : GeometricObject { … } public class TestProgram { public static void Main(…) { … } … }

55 Assoc. Prof. Stoyan Bonev 11/23/2015 55 class GeometricObject F Inheritance illustrated as skeletal C# source See detailed source text in file ProgGeometricObject.cs

56 Assoc. Prof. Stoyan Bonev 11/23/2015 56 Task 1 F 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

57 Assoc. Prof. Stoyan Bonev 11/23/2015 57 Task 2 F 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

58 11/23/2015Assoc. Prof. Stoyan Bonev58 C# Programming: From Problem Analysis to Program Design58 Part 2 POLYMORPHISM In C#

59 11/23/2015Assoc. Prof. Stoyan Bonev59 C# Programming: From Problem Analysis to Program Design59 Advanced OOP Features after BDoyle Polymorphism in C# C# Programming: From Problem Analysis to Program Design 3rd Edition 11

60 11/23/2015Assoc. Prof. Stoyan Bonev60 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

61 11/23/2015Assoc. Prof. Stoyan Bonev61 C# Programming: From Problem Analysis to Program Design61 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

62 C# Programming: From Problem Analysis to Program Design62 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

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 Design63

64 11/23/2015Assoc. Prof. Stoyan Bonev64 Extract from Java lecture 14 Polymorphism

65 Assoc. Prof. Stoyan Bonev 11/23/2015 65 Polymorphism F A subclass is a specialized form of its superclass. F Every instance of a sub class is an instance of a superclass BUT not vice versa. F Example: Every circle is a geometric object, BUT not every geometric object is a circle. F You can always assign an instance of a subclass to a reference variable of its superclass type. F You can always pass an instance of a subclass as a parameter/argument of its superclass type.

66 Assoc. Prof. Stoyan Bonev 11/23/2015 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()

67 Assoc. Prof. Stoyan Bonev 11/23/2015 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()

68 Assoc. Prof. Stoyan Bonev 11/23/2015 68 Comments F Ref variable o is Object type. F Array ref variable arr is Object type. F We can assign any instance of Object ((eg. New Base, new Derived1, or new Derived2 to o or to arr array element F 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. F This feature is known as polymorphism.

69 Assoc. Prof. Stoyan Bonev 11/23/2015 69 Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes C 1, C 2,..., C n-1, and C n, where C 1 is a subclass of C 2, C 2 is a subclass of C 3,..., and C n-1 is a subclass of C n. That is, C n is the most general class, and C 1 is the most specific class. In Java, C n is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C 1, C 2,..., C n-1 and C n, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

70 Assoc. Prof. Stoyan Bonev 11/23/2015 70 COS240 O-O Languages AUBG, COS dept Formal transition from Polymorphism in Java context To Polymorphism in C# context Source:Lec Java Polymorphism

71 Assoc. Prof. Stoyan Bonev 11/23/2015 71 COS240 O-O Languages AUBG, COS dept Same formal rules as in case of Inheritance

72 Assoc. Prof. Stoyan Bonev 11/23/2015 72 Dynamic binding in C# F From Java to C#  Sub folder: \Polymorphism Demo Programs  Java program: ProgBaseDerv1Derv2.java  C# program: ProgBaseDerv1Derv2.cs

73 Assoc. Prof. Stoyan Bonev 11/23/2015 73 Dynamic binding in C# F From Java to C#  Sub folder: \Polymorphism Demo Programs  Java program: ProgramCircle3Cylinder3.java  C# program: ProgramCircle3Cylinder3.cs

74 Thank You for Your attention! Look ahead!

75 Abstract classes

76 C# Programming: From Problem Analysis to Program Design76 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

77 C# Programming: From Problem Analysis to Program Design77 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

78 C# Programming: From Problem Analysis to Program Design78 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

79 C# Programming: From Problem Analysis to Program Design79 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

80 C# Programming: From Problem Analysis to Program Design80 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

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 Design82

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 Design83

84 Partial classes

85 C# Programming: From Problem Analysis to Program Design85 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

86 Interfaces

87 C# Programming: From Problem Analysis to Program Design87 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

88 C# Programming: From Problem Analysis to Program Design88 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

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 C# Programming: From Problem Analysis to Program Design89 Review PresentationGUIWithAbstractClassAndInterface Example

90 Thank You for Your attention!


Download ppt "11/23/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 35 Title: C# vs. Java Inheritance & Polymorphism Reference: COS240 Syllabus."

Similar presentations


Ads by Google