Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
INF230 Basics in C# Programming AUBG, COS dept Lecture 25 Title: Object-Oriented Programming (part 5 - Interfaces) Reference: Doyle, chap 11 Chapter 11 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program Design 4th Edition Lecture Contents: • • • • • Abstraction Encapsulation Inheritance Polymorphism Abstract classes • Interfaces • Generics Object-Oriented Language Features • Abstraction: Generalizing, identifying essential features, hiding nonessential complexities • Encapsulation; Packaging data and behaviors into a single unit, hiding implementation details • Inheritance: Extending program units to enable reuse of code • Polymorphism: Providing multiple (different) implementations of same named behaviors • Abstract classes: Serve to define a high-level abstract object, that can then be used as a base class for many different derived related classes. • Interfaces – The interface of a class defines how it should behave. – An interface is for defining common behavior for classes (incl. unrelated classes). C# Programming: From Problem Analysis to Program Design 4 Prelude To Interfaces, i.e. Multiple Inheritance Interfaces • A superclass defines common behavior for related subclasses • An interface can be used to define common behavior for classes (incl. unrelated classes) • Inheritance associates “is a” relationship • Interfaces associate “has a” relationship Interfaces • Interfaces enable the developer to truly separate the “What?” from the “How?”. • J. Sharp Interfaces & Abstract Classes The Interface concept Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 Interface No method bodies – just method header. Must provide implementation when used. public interface Driver { void turnWheel(double angle); void pressAccelerator(double amount); void pressBrake(double amount); } public class BusDriver : Driver { // must include implementation for each of the three methods from Driver } 9 May also have public class BusDriver : Person, Driver { // must include implementation for each of the three methods from Driver } This is a “back door” approach to multiple inheritance Single inheritance via base class and extra inheritance via interfaces 10 Interfaces More details Interfaces • C# supports single inheritance – Only inherit from a single class, abstract or non abstract – Classes can implement any number of interfaces • Think of an interface as a class that is totally abstract; all methods are abstract – Abstract classes can have abstract methods 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 12 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 13 Interfaces Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Interfaces Interface is class-like construct that contains only constants and abstract methods. Interface is similar to abstract class, but its intent is to specify common behavior for objects that belong even to different inheritance hierarchies. Reminder1: Abstract class contain regular methods and abstract methods and polymorphic approach is within one only specific inheritance hierarchy. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 Interfaces To distinguish an interface from a class, C# uses interface reserved word: public interface Edible { string howToEat(); } You cannot create an instance of interface with new You can use interface as data type for ref var, or as a result of casting Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Interface example Given: Edible interface and two separate independent inheritance hierarchies: =================================================================================================== Animal ↑ ↑ Tiger Chicken(Edible) Fruit(Edible) ↑ ↑ Apple Orange =================================================================================================== Animal – regular base class Fruit – base class implements Edible interface Chicken – child class implements Edible interface Tiger – regular child class Apple, Orange – regular child classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Open file InterfaceExample02Edible.cs using Edible interface to specify which object is edible, in other words has implemented method howToEat(). Task: Browse the source text Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 Open file InterfaceExample02Edible.cs Chicken extends Animal, implements Edible to specify that chickens are edible, implements method howToEat() Tiger extends Animal, does not implement Edible i.e. tigers are not edible, no need to implement method howToEat() Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Open file InterfaceExample02Edible.cs public interface Edible { string howToEat(); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Open file InterfaceExample02Edible.cs abstract class Animal { } // empty class class Chicken : Animal, Edible { public string howToEat() { return "Chicken: Fry it"; } } class Tiger : Animal { } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Open file InterfaceExample02Edible.cs Fruit implements Edible, and does not implement howToEat() method. Therefore Fruit is to be modified as abstract class and concrete subclasses of Fruit must implement howToEat() method, as it is done with Apple class and Orange class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Open file InterfaceExample02Edible.cs public interface Edible { string howToEat(); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 Open file InterfaceExample02Edible.cs abstract class Fruit { } class Apple : Fruit, Edible { public string howToEat() { return "Apple: Make apple juice"; } } class Orange : Fruit, Edible { public string howToEat() { return "Orange: Squeeze it"; } } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 Open file InterfaceExample02Edible.cs Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 C# supported interfaces Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 C#(.NET) supported interfaces: IComparable Problem: we need a method to return the larger of two objects of the same type: Two students, Two dates, Two circles, Two rectangles It is must the two (both) objects to be comparable Comparability is considered a common behavior C# provides IComparable interface for this purpose public interface Icomparable { int CompareTo(object o); { Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Java supported interfaces: IComparable Many C# predefined classes (string, Date) implement IComparable interface to define an order for the objects. String, Date classes provide CompareTo() method. Their definition is like this: //------------------------------------public class string : object , IComparable { // class body } //------------------------------------Public class Date : object, IComparable { // class body } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Java supported interfaces: Comparable Given string s; Date d; //------------------------------(s instanceof string) is true (s instanceof Object) is true (s instanceof Comparable) is true //------------------------------(d instanceof Date) is true (d instanceof Object) is true (d instanceof Comparable) is true Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 User Defined class implement interfaces: IComparable Reminder : class Rectangle We cannot compare instances of Rectangle, because Rectangle does not implement IComparable interface How to proceed? – Re edit Rectangle class to implement IComparable OR – Create new class ComparableRectangle to extend Rectangle and to implement IComparable Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 User Defined class implement interfaces: IComparable First option solution Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 User Defined class implement interfaces: IComparable Solution scheme for the first option: GeometricObject IComparable | | Rectangle - - - - - - - - Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 User Defined class implement interfaces: IComparable Open source file ProgComparableRectangle.cs Source text skeleton for Rectangle public class Rectangle : GeometricObject , IComparable { . . . public int CompareTo(object o) {…} } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 User Defined class implement interfaces: IComparable How to define the CompareTo() method. We need a comparison criteria. For example, rectangle width size class Rectangle : GeometricObject, IComparable { . . . public int CompareTo(object o) { if (this.width == ((Rectangle)o).width) return 0; else if (this.width < ((Rectangle)o).width) return -1; else return 1; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 34 reserved. 0132130807 } // end of class rights Rectangle User Defined class implement interfaces: IComparable How to use the CompareTo() method Rectangle Rectangle Rectangle Rectangle r1 r2 r3 r4 = = = = new new new new Rectangle(10.0,20.0); Rectangle(10.0, 20.0); Rectangle(20.0, 20.0); Rectangle(5.0, 20.0); Console.WriteLine(r1.CompareTo(r2)); Console.WriteLine(r1.CompareTo(r3)); Console.WriteLine(r1.CompareTo(r4)); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 User Defined class implement interfaces: IComparable Expected output? Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 User Defined class implement interfaces: IComparable Second option solution Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 User Defined class implement interfaces: IComparable Solution scheme for the second option: GeometricObject ↑ Rectangle IComparable ↑ ↑ ComparableRectangle - - - - - Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 User Defined class implement interfaces: IComparable Open source file ProgComparableRectangle.cs Source text skeleton for ComparableRectangle public class ComparableRectangle : Rectangle , IComparable { public ComparableRectangle(…) { …} public int CompareTo(object o) {…} } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 User Defined class implement interfaces: IComparable How to use the CompareTo() method ComparableRectangle r1 = new ComparableRectangle(4.,5.); ComparableRectangle r2 = new ComparableRectangle(4.,6.); ComparableRectangle r3 = new ComparableRectangle(5.,4.); Console.WriteLine(r1.CompareTo(r2)); Console.WriteLine(r1.CompareTo(r3)); Console.WriteLine(r2.CompareTo(r1)); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 User Defined class implement interfaces: IComparable Expected output? Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Open file InterfaceExample01Traveler.cs Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 Open file InterfaceExample03.cs Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Conclusion Abstract class contain – regular methods and – abstract methods and polymorphic approach is within one only specific inheritance hierarchy. GeometricObject, Circle, Rectangle Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Conclusion Interface contains only abstract methods. Interface is similar to abstract class, but its intent is to specify common behavior for objects that belong even to different inheritance hierarchies Animal, Tiger, Chicken (Edible interface) Fruit (Edible interface), Apple, Orange Interface is a back door to implement multiple inheritance in Java Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Run Demo programs on Interfaces Interfaces Practice Defining an Interface • Can be defined as member of existing namespace or class OR by compiling it to separate DLL • Easy approach is to put the interface in a separate project (like was done with Person and Student) – Use the Class Library template from Start page • Unlike abstract classes, it is not necessary to use the abstract keyword with methods of interfaces – Because all methods are abstract Review LibraryFiles Example C# Programming: From Problem Analysis to Program Design 48 Defining an Interface (continued) To store in Class Library, Build the interface DLL using Build option from BUILD menu Figure 11-15 ITraveler interface C# Programming: From Problem Analysis to Program Design 49 Implement the Interface • Follow same steps as with the Person and Student DLLs …if you want to store in Class Library – Create Class Library File from Start page – Compile and Build assembly from BUILD menu option, creating a .DLL file – In the class implementing the interface, Add Reference to the .DLL file – Type a using statement (for the namespace identifier) in the class implementing the interface C# Programming: From Problem Analysis to Program Design 50 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 51 Implement the Interface: PresentationGUI Application Populated by Interface methods Figure 11-16 PresentationGUI output using interface methods C# Programming: From Problem Analysis to Program Design 52 Implement the Interface: PresentationGUI Application • GetStartLocation( ), GetDestination( ), and DetermineMiles( ) members of ITraveler interface private void btnTravel_Click(object sender, EventArgs e) { // GetStartLocation( ), GetDestination( ) and DetermineMiles( ) // methods all defined as abstract methods in ITraveler interface txtBxFrom.Text = aStudent.GetStartLocation(); txtBxTo.Text = aStudent.GetDestination(); txtBxMiles.Text = aStudent.DetermineMiles().ToString(); txtBxFrom.Visible = true; … //More statements C# Programming: From Problem Analysis to Program Design 53 .NET Framework Interfaces • Play an important role in the .NET Framework – Collection classes such as Array class and HashTable class implement a number of interfaces • Designing the classes to implement interfaces provides common functionality among them C# Programming: From Problem Analysis to Program Design 54 .NET Framework Interfaces (continued) • .NET Array class is an abstract class – Array implements several interfaces (ICloneable; IList; ICollection; and IEnumerable) • Includes methods for manipulating arrays, such as: – Iterating through the elements – Searching by adding elements to the array – Copying, cloning, clearing, and removing elements from the array – Reversing elements – Sorting • Much of functionality is in place because of the contracts the interfaces are enforcing C# Programming: From Problem Analysis to Program Design 55 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 56 Polymorphic Programming in .NET • Multiple classes can implement the same interface, each providing different implementation details for its abstract methods – “Black box” concept • Classes that derive from abstract classes are forced to include implementation details for any abstract method C# Programming: From Problem Analysis to Program Design 57 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 58 Thank You For Your Attention!