Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming (part 4 – Abstract Classes)

Similar presentations


Presentation on theme: "Object-Oriented Programming (part 4 – Abstract Classes)"— Presentation transcript:

1 Object-Oriented Programming (part 4 – Abstract Classes)
INF230 Basics in C# Programming AUBG, COS dept Lecture 24 Title: Object-Oriented Programming (part 4 – Abstract Classes) Reference: Doyle, chap 11

2 Chapter 11 Advanced Object-Oriented Programming Features
C# Programming: From Problem Analysis to Program Design 4th Edition

3 Lecture Contents: Abstract classes Abstraction Encapsulation
Inheritance Polymorphism Abstract classes Interfaces Generics

4 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 Abstract classes serve to define a high-level abstract object, that can then be used as a base class for many different derived classes. Interfaces: An interface is for defining common behavior for classes (incl. unrelated classes). The interface of a class defines how it should behave

5 Abstract classes must not be considered as an isolated independent entity
Abstract classes are to be considered within the context of Inheritance, Polymorphism & Dynamic Binding

6 Reminder: One more aspect/view
polymorphism

7 Polymorphism Inheritance is a relation that enables a sub class to inherit features from its superclass with additional new features. 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 actual argument /instance of a subclass type/ to meet corresponding formal parameter /instance of its superclass type/.

8 Consider code in C# // source text file: ProgBaseDerv1Derv2.cs
given inheritance hierarchy Object | Base | | Derived1 Derived2 Classes Base, Derived1, Derived2 provide method toString() and method show()

9 Consider code class Base {
public void show() { Console.WriteLine("Base " );} public String toString() { return "\n\nBase"; } } // end of class Base class Derived1 : Base { public void show() {Console.WriteLine("Derived1" );} public String toString() { return "\n\nDerived1"; } } // end of class Derived1 class Derived2 : Base { public void show() {Console.WriteLine("Derived2" );} public String toString() { return "\n\nDerived2"; } } // end of class Derived2

10 Consider code public class ProgBaseDerv1Derv2 {
public static void Main(string[] args) { Object o = new Object(); Base a = new Base(); a.show(); Derived1 b = new Derived1(), b.show(); Derived2 c = new Derived2(), 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++) { Console.WriteLine( arr[i].toString()); arr[i].show();} // o is named polymorphic variable o=a; o=b; o=c; a=b; a=c; } // end of method main() } // end of class ProgBaseDerv1Derv2

11 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.

12 Consider code // source text file: ProgPolymorphismDemo.cs
given inheritance hierarchy Object | GeometricObject | | Circle Rectangle

13 Consider code public static void Main(string args[]) { displayObject(new Circle(1, "red", false)); displayObject(new Rectangle(1, 1, "blue", true)); Circle aa = new Circle(1, "red", false); displayObject(aa); Rectangle bb = new Rectangle(1, 1, "blue", true); displayObject(bb); } // end of main public static void displayObject( GeometricObject o) { Console.WriteLine("Created:"+o.getDateCreated()+" color:"+o.getColor()+" Filled:"+o.isFilled()); // or Console.WriteLine("Created:"+o.dateCreated+" color:"+o.color+" Filled:"+o.filled); }

14 Comments The formal param is GeometricObject o.
The actual argument may be any instance of GeometricObject (eg. New Circle or new Rectangle) 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 (formal param) can point to an object of its sub class type (actual arg). This feature is known as polymorphism.

15 Dynamic Binding // file: ProgGeometricObject3.cs
Object o = new GeometricObject(); Console.WriteLine (o.toString()); Object aa = new Circle(1); Console.WriteLine (aa.toString()); Q. Which toString() method is invoked by o and by aa? Before answer, let introduce two terms: declared type actual type

16 Dynamic Binding Object o = new GeometricObject();
A variable must be declared a type. The type of a variable is called its declared type. o’s declared type is Object. The actual type is the actual class for the object referenced by the variable o’s actual type is GeometricObject Which toString() method is invoked by o is determined by o’s actual type. This is known as dynamic binding

17 Dynamic Binding Given a hierarchy of classes: C1, C2, ..., Cn-1, Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., 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. Dynamic binding works as follows: Suppose an object o is an instance of class C1. If o invokes a method p, the VM 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.

18 Casting Objects You have already used the casting operator to convert variables of one primitive type to another. double d1=3.156, d2; int i1, i2=55; // casting – convert from int to double d2 = i2; // allowed d2 = (double)i2; // allowed // casting – convert from double to int i1 = d1; // compiler error i1 = (int) d1; // allowed Same approach applied when casting objects

19 TIP To help understand casting, you may also consider the analogy of fruit, apple, and orange with the Fruit class as the superclass for Apple and Orange. An apple is a fruit, so you can always safely assign an instance of Apple to a variable for Fruit. However, a fruit is not necessarily an apple, so you have to use explicit casting to assign an instance of Fruit to a variable of Apple.

20 Casting from Superclass to Subclass
Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Apple x = (Apple)fruit; // explicit casting only allow Orange x = (Orange)fruit; Apple x = fruit; // implicit casting not allowed

21 Casting from Subclass to Superclass
Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Fruit f1 , f2; Apple apl = new Apple(); f1 = apl; // implicit casting allowed f2 = (Fruit)apl; // explicit casting allowed

22 Casting from Superclass to Subclass
Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Object o = new GeometricObject(); Circle ac = new Circle(); ac = o; // syntax error, not every geometric object is necessarily a circle. ac = (Circle) o; // OK, but casting may not always succeed

23 Casting from Subclass to Superclass
Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Object o = new GeometricObject(); Circle ac = new Circle(); o=ac; o = (GeometricObject)ac; o = (Circle)ac;

24 Thank You For Your Attention!

25 Prelude to Abstract Classes
Reminder: polymorphism Dynamic Binding

26 Prelude to Abstract Classes
If you move from super class down to sub class, classes become more specific and more concrete. If you move from sub class up to super class, classes become more general and less specific Sometimes super class is so abstract that it cannot have any specific instances. Such a class is referred to as an ABSTRACT CLASS

27 Abstract classes More details

28 Abstract classes An abstract class is a class where some methods are unspecified (defined signature only). The unspecified methods are declared abstract. The class also is declared abstract. An abstract class cannot be used to create objects. You cannot instantiate objects of an abstract type. An abstract class must be sub-classed. It contains abstract methods, which are implemented in concrete subclasses.

29 Abstract Class Example
May have defined methods and abstract methods. abstract class CacheFile { string filename; byte[] contents; void flush() { // Write file to disk } void refresh() { // Load file from disk abstract string deserialize(); abstract byte[] serialize(string s); These methods are defined These methods are abstract because how you want to store data into the file is application-dependent 29

30 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

31 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

32 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. Base class can have data and method members [access modifier] abstract class ClassIdentifier { } // Base class Objects can only be created using classes derived from the abstract class C# Programming: From Problem Analysis to Program Design

33 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

34 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

35 Abstract Methods (continued)
Defined in Person // Classes that derive from Person // must provide implementation details // (the body for the method) public abstract string GetExerciseHabits( ); In the derived class, all abstract methods’ headings include the special keyword override public override string GetExerciseHabits() { return "Exercises daily"; } Defined in Student C# Programming: From Problem Analysis to Program Design

36 Abstract classes practice

37 Demo program AbstractClass01.cs
Given two classes Class CC1 – abstract base class Data member – int n No argument constructor Abstract method display() – signature only Class CC2 – derived from CC1 Regular method display() – qualified override Class Program Main() method only

38 Demo program AbstractClass01.cs
public abstract class CC1 { public int n; public CC1() Console.WriteLine("Inside Abstract class CC1 Constructor..."); Console.Write("Enter a number = "); n = Convert.ToInt32(Console.ReadLine()); } public abstract void display(); } // end of class

39 Demo program AbstractClass01.cs
public class CC2 : CC1 { public override void display() Console.WriteLine("n = " + n.ToString()); Console.WriteLine("n = {0}",n.ToString()); Console.WriteLine("n = {0}", n); } } // end of class

40 Demo program AbstractClass01.cs
class Program { static void Main(string[] args) CC1 obj; // this is only reference var, CC2 obj1 = new CC2(); //create object obj = obj1; obj.display(); obj1.display(); }

41 Demo program AbstractClass01.cs
Type, compile and run the demo What is the expected output?

42 Demo program AbstractClass01.cs
Modify the source code by adding no argument constructor for CC2 class: public CC2() { Console.WriteLine("Inside CC2 Constructor..."); } Type, compile and run the modified demo What is the expected output?

43 Demo program AbstractClass01.cs
Modify the source code by changing the access qualifiers for data member n and constructor CC1() from: public int n; public CC1() { … } to protected int n; protected CC1() { … } Type, compile and run the modified demo It is OK, isn’t it!!!

44 Demo program AbstractClass01.cs
Modify the source code by changing the access qualifiers for data member n and constructor CC1() from: public int n; public CC1() { … } to private int n; protected CC1() { … } Type, compile and run the modified demo It is not OK, is it!!!

45 Demo program GeometricObjectAbstractClass.cs
Reminder: GeometricObject.cs was introduced in lecture on Inheritance

46 GeometricObject – Circle, Rectangle
GeometricObject | | Circle Rectangle Common properties for both Circle and Rect: Color, filled/nofilled, dateCreated Circle – specific property: radius Rectangle – specific properties: width, height

47 GeometricObject – Circle, Rectangle
| | Circle Rectangle Common properties for both Circle and Rect: Color, filled/nofilled, dateCreated Circle – specific behavior: getArea(), getPerimeter() Rectangle – specific behavior:

48 GeometricObject – Circle, Rectangle
| | Circle Rectangle Common properties for both Circle and Rect: Color, filled/nofilled, dateCreated Circle – specific property and behavior: Radius, getArea(), getPerimeter() Rectangle – specific properties and behavior: width, height, getArea(), getPerimeter()

49 Inheritance hierarchy
Is it reasonable to generalize getArea(), getPerimeter() methods? From one side: Since we can compute area and perimeter for all geometric objects, it is better to define getArea(), getPerimeter() as methods in super class GeometricObject. From other side: Both methods cannot be implemented in the base class because their implementation depends on specific properties (radius or height/width) of the geometric object defined in the sub classes. Such methods are referred to as abstract methods and are denoted in the super class using modifier abstract. Class with abstract methods becomes an abstract class and is must to be also denoted abstract. See next slide.

50 Open file ProgGeometricObjectAbstractClass.cs
abstract class GeometricObject { … public abstract double getArea(); public abstract double getPerimeter(); } You cannot create instances of abstract classes using new operator. Constructors in abstract classes are protected because they are used only by subclasses. Super class defines common features (incl. methods getArea() and getPerimeter()). Because you don’t know how to compute area and perimeter of geometric objects, both methods are defined as abstract methods. These methods are implemented/overridden in the subclasses.

51 Open file ProgGeometricObjectAbstractClass.cs
class Circle : GeometricObject { … public override double getArea() { return Math.PI * radius * radius; } public override double getPerimeter() { return 2 * Math.PI * radius; } public override string toString() {return "Circle:\n"+base.toString();} } // end of class

52 Open file ProgGeometricObjectAbstractClass.cs
class Rectangle : GeometricObject { … public override double getArea() { return width * height; } public override double getPerimeter() { return 2 * (width + height); } public override string toString(){ {return "RecRec:\n"+base.toString();} } // end of class

53 Open file ProgGeometricObjectAbstractClass.cs
Why do we need abstract methods? What benefits if any? Browse the main() method: It creates two geometric objects – circle, rectangle Invokes equalArea() method – have a careful look at the formal parameters type Invokes displayGeometricObject() method – have a careful look at the formal parameter type

54 Open file ProgGeometricObjectAbstractClass.cs
public class ProgGeometricObjectAbstractClass { static void Main( string[] args) GeometricObject geo1 = new Circle(5.0); GeometricObject geo2 = new Rectangle(5.0, 3.0); Console.WriteLine("The two object have same area? "+ equalArea(geo1, geo2) ); displayGeometricObject(geo1); displayGeometricObject(geo2); GeometricObject[] o = { new Circle(2.0), new Circle(3.0), new Rectangle(5.0, 3.0), new Rectangle(4.0,6.0) }; for (int i=0; i< o.Length; i++) Console.WriteLine("The two object have same area? "+ equalArea(geo2, o[i]) ); } // end of Main

55 Open file ProgGeometricObjectAbstractClass.cs
static bool equalArea( GeometricObject o1, GeometricObject o2) { return o1.getArea() == o2.getArea(); } static void displayGeometricObject(GeometricObject o) Console.WriteLine(); Console.WriteLine(o.toString() ); Console.WriteLine("The area is " + o.getArea() ); Console.WriteLine("The perimeter is " + o.getPerimeter() );

56 Open file ProgGeometricObjectAbstractClass.cs
Thanks to declaring abstract methods in super class, it is valid to create a connection btw super class and sub classes through getArea()/getPerimeter() methods and apply the polymorphic approach or in other words: Reference variable of a super class type (formal parameter) can point to an object of its sub class type (actual argument – look at its actual type).

57 Open file ProgGeometricObjectAbstractClass.cs
Equalarea() method to have two parameters GeometricObject and to compare to equality the area of a circle and the area of a rectangle. public static boolean equalArea(GeometricObject o1, GeometricObject o2) { return o1.getArea() == o2.getArea(); }

58 Open file ProgGeometricObjectAbstractClass.cs
displayGeometricObject() method to have a parameter GeometricObject and to display: the area and perimeter of a circle or the area and perimeter of a rectangle (depends on actual argument) when method called. public static void displayGeometricObject(GeometricObject o) { Console.WriteLine("The area is " + o.getArea() ); Console.WriteLine("Perimeter is "+o.getPerimeter()); } // end of method

59 Inheritance, polymorphism and abstract classes
Given the source: GeometricObject geo1 = new Circle(5.0); GeometricObject geo2 = new Rectangle(5.0, 3.0); GeometricObject[] o = { new Circle(2.0), new Circle(3.0), new Rectangle(5.0, 3.0), new Rectangle(4.0,6.0) }; for (int i=0; i< o.Length; i++) Console.WriteLine("The two objects have same area?" equalArea(geo1,o[i])); Q.: Can you guess/predict the expected output?

60 Inheritance, polymorphism and abstract classes
Given the source: GeometricObject geo1 = new Circle(5.0); GeometricObject geo2 = new Rectangle(5.0, 3.0); GeometricObject[] o = { new Circle(2.0), new Circle(3.0), new Rectangle(5.0, 3.0), new Rectangle(4.0,6.0) }; for (int i=0; i< o.Length; i++) Console.WriteLine("The two objects have same area?" equalArea(geo2,o[i])); Q.: Can you guess/predict the expected output?

61 Inheritance, polymorphism and abstract classes
Expected output: Geo1 Geo2 ======================= false false false true

62 Digression on equalArea() problem
The task to compare the area of a circle and the area of a rectangle could be solved without specifying abstract class GeometricObject and erasing the getArea()/getPerimeter() methods from the super class. BUT: such a solution should lose the advantages provided when using polymorphism

63 Sealed classes

64 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

65 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

66 Partial classes

67 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

68 Creating Partial Classes
All the files must use the partial keyword All of the partial class definitions must be defined in the same assembly (.exe or .dll file) Class name and accessibility modifiers, such as private or public, must also match // class definition split into two or more source files public partial class ClassIdentifier C# Programming: From Problem Analysis to Program Design

69 Thank You For Your Attention!


Download ppt "Object-Oriented Programming (part 4 – Abstract Classes)"

Similar presentations


Ads by Google