Presentation is loading. Please wait.

Presentation is loading. Please wait.

2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat.

Similar presentations


Presentation on theme: "2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat."— Presentation transcript:

1 2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat

2 2009 first semister Instructor: Abdalrahman Obidat 2 Classes and Inheritance Classes have proven very useful –They help us write programs the way we view the world: interface vs implementation C# supports object oriented programming, i.e., –Inheritance (sub classing) –Dynamic dispatch (polymorphism) Two very powerful programming tools! –They help us write less code

3 2009 first semister Instructor: Abdalrahman Obidat 3 Composition: has-a relationship We have used many times several classes together, e.g., –Use an instance of a class as an instance field of another class public class Landscape { private Mountain m = new Mountain(); } This a "has-a" relationship –A Landscape "has-a" Mountain Also called aggregation

4 2009 first semister Instructor: Abdalrahman Obidat 4 Organization hierarchy Often, we classify things according to a hierarchy (from general to specific), e.g. part of the organization of a university UniversityMember Staff Faculty Lecturer Professor Student Freshman Sophomore

5 2009 first semister Instructor: Abdalrahman Obidat 5 Inheritance: is-a relationship Objects have also an "is-a" relationship –A Freshman "is-a" Student, a Lecturer "is-a" UniversityMember C# gives us the tools to implement an "is-a" relation. We can map our view of the world on the computer

6 2009 first semister Instructor: Abdalrahman Obidat 6 Inheritance in C# Inheritance is a way to encode the "is-a" relation in OO languages –Freshman declares that it "is-a" Student by inheriting from it –A derived class inherits from a base class by writing " : BaseClassName " in the derived class declaration public class Freshman : Student { /* Freshman-specific stuff here */} derived class (or subclass) base class (or superclass)

7 2009 first semister Instructor: Abdalrahman Obidat 7 What is inherited? (1) The subclass inherits all of the members (data +methods) of its superclass exept private members. Members declared public or protected within the superclass can be used by the subclass as if they were declared within the subclass itself. protected member of a class: visible within the class itself and the subclasses (even if they are in a different assembly). More on protected later.

8 2009 first semister Instructor: Abdalrahman Obidat 8 What is inherited? (2) private members of the superclass are unavailable outside the superclass scope. assembly level (=declared internal) members of the superclass are unavailable outside the assembly scope. If the superclass and subclass are in the same assembly, the subclass can access any assembly level members of the superclass A subclass instance is also a superclass instance (is- a relation) but superclass instant is not a subclass instant. –All methods of the superclass can be used on a subclass instance.

9 2009 first semister Instructor: Abdalrahman Obidat 9 Scope example Base.cs public class Base { public int i; //visible everywhere internal int j;//visible within the assembly protected int k; //visible within //any derived class private int l;// visible within Base only } Derived.cs public class Derived: Base{ public void update(){ i=4; // OK j=5; // OK if in the same assembly // Error if not in the same assembly k=6; // OK l=7; /*Error (not in Base)*/}}

10 2009 first semister Instructor: Abdalrahman Obidat 10 Example: Person, Student A person has a name, an age and can speak A student is a person with a gpa Person name: String age: int speak: void Student gpa: double derived from

11 2009 first semister Instructor: Abdalrahman Obidat 11 Person class public class Person{ public String name; // any name is OK private int age; // 0<=age<=130 //Call the other constructor public Person():this("someone",20) {} public Person(String s, int a) { name = s; Age = a; } public int Age{ // Age property set {if (value>=0 && value<=130) age=value;} get {return age;} } public void speak() { Console.WriteLine("Hi, I am "+name);} }

12 2009 first semister Instructor: Abdalrahman Obidat 12 Student class public class Student: Person{ private double gpa; //between 0 and 4.0 public Student()//Person() automatically called { gpa = 3.5; } public Student(String s,int a,double g) :base(s,a)//Call the constructor Person(s,a) { gpa = g; } public double GPA { // GPA property set{ if (value>=0 && value<=4.0) gpa=value;} get{ return gpa;} } }

13 2009 first semister Instructor: Abdalrahman Obidat 13 Using Person and Student Person p = new Person("Jane",25); Student s = new Student("Robert",28,3.8); p.speak(); // a person can speak s.speak(); // a student can speak, since // a student is a person Person p1 = new Person() Student s2 = new Student()

14 2009 first semister Instructor: Abdalrahman Obidat 14 Method overriding How can we specialize speak for the Student class? Define speak as virtual in the Person class public virtual void speak(){ /*code*/ } Redefine speak within the Student class public override void speak(){ base.speak();//let the Person speak // Add what the student say Console.WriteLine("My gpa is "+gpa); } For any Student instance s, s.speak() invokes the speak method of the Student class. This is called method overriding.

15 2009 first semister Instructor: Abdalrahman Obidat 15 this keyword revisited this: two uses –a reference to the current object when within one of the object instance methods –Use this(argument list) when calling another constructor from a constructor (within the same class). The call is the first executed statement in the constructor. public Person(): this(name,20) { /* more code here if necessary */ }

16 2009 first semister Instructor: Abdalrahman Obidat 16 base keyword base: two uses –a reference to the base object part of the current derived object within one of the derived object instance method. base.speak();//In Student.speak() –Use base(argument list) when calling a base constructor from a derived constructor. The call is the first executed statement in the constructor. public Student(string s, int a, double g): base(s,a) { gpa = g; } –Can't chain the base calls base.base.method();//Error

17 2009 first semister Instructor: Abdalrahman Obidat 17 Constructor calls When calling a constructor, C# –invokes the base class constructor (if necessary via an implicit call to base()), –then, initializes the instance variables of the class, –then, executes the statements in the constructor. public class Derived: Base{ private int i=3; public Derived(){i++;}} // And in some method in some other class Derived d = new Derived(); // call Base(), initialize any instance field // in class Base, execute Base(), // set i to 3 in class Derived, // increment i as instructed in Derived() // What happens if Base is derived from // some other class?

18 2009 first semister Instructor: Abdalrahman Obidat 18 Overloading and Overriding Method overloading: same name but a different number or type of arguments. –A subclass can define some overloaded methods that augment the inherited overloaded methods provided by a base class. Method overriding: define a method in the subclass with the same signature (return type and arguments) as the inherited method. –The method in the subclass shadows the method of the superclass. –Powerful when dealing with a hierarchy of objects (polymorphism: next slide)

19 2009 first semister Instructor: Abdalrahman Obidat 19 Polymorphism example Consider Person[] group=new Person[2]; group[0]=new Person("Jane",25); group[1]=new Student("Bob",26,3.9); //OK, a Student is a Person for(int i=0; i<2; i++) group[i].speak(); // What is printed? Note: Properties are just syntactic sugar for get and set methods. Overriding works the same way for instance properties as for instance methods.

20 2009 first semister Instructor: Abdalrahman Obidat 20 Polymorphism If there are several implementations of a virtual method in the inheritance hierarchy of an object, the one in the most derived class always overrides the others. This is the case even if we refer to the object by way of a less derived type. group[1].speak(); //invokes speak of Student //even though group is an // array of type Person[]

21 2009 first semister Instructor: Abdalrahman Obidat 21 Dynamic binding and Polymorphism Polymorphism uses dynamic binding –The selection of the method is done at run time. The CLR looks at the actual type of the object referred to. To turn on overriding, the C# programmer must mark the base instance method as virtual and the derived instance method as override (it is a compiler error to do one without the other). To prevent overriding of a method, just don't use virtual. However, it is possible to shadow the method in a derived class by marking it as new (see next slide).

22 2009 first semister Instructor: Abdalrahman Obidat 22 new keyword on a method // in Person public void speak(){Consol.WriteLine(“person”)} //can't override since not virtual // in Student public new void speak(){Consol.WriteLine(“Student”} // shadows speak in Person // in some method of some other class Student s = new Student(); s.speak(); // Student.speak,print Student Person p = s; p.speak(); // Person.speak (static binding),Print person // With overriding, Student.speak would // have been called.

23 2009 first semister Instructor: Abdalrahman Obidat 23 Static binding When the overriding feature is turned off (no virtual keywork), the compiler uses the static type of the variable to select the instance method. Static binding is slightly more efficient than dynamic binding.

24 2009 first semister Instructor: Abdalrahman Obidat 24 Static methods (1) Reminder: static methods are not attached to any instance of a class. They belong to the class. A static method is invoked by using the class name. They are bound at compile time. (That's why they are called static) Math.Sqrt(2); A class inherits all of the public and protected static methods of a base class. But there is no overriding mechanism with static methods. –However, you can shadow a base class static method in the subclass (using the keyword new as for a non virtual instance method).

25 2009 first semister Instructor: Abdalrahman Obidat 25 Static methods (2) public class Base{ public static void foo(){ Console.WriteLine("foo of Base");} } public class Derived: Base{ public static void foo(){// No Console.WriteLine("foo of Derived");} public new static void foo(){ // OK Console.WriteLine("foo of Derived");} }

26 2009 first semister Instructor: Abdalrahman Obidat 26 sealed keyword The class can't be inherited. public sealed class ThisIsIt{ /* class code */ } public class MoreOfIt: ThisIsIt {} // Error A class that is declared sealed cannot be a base class (i.e., a class cannot extend a sealed class). All methods in a sealed class are implicitly sealed. (ex. Class string is a sealed class. This class cannot be extended )

27 2009 first semister Instructor: Abdalrahman Obidat 27 A method declared sealed in a base class cannot be overridden in a derived class. Methods that are declared private are implicitly sealed, because it is impossible to override them in a derived class Methods that are declared static also are implicitly sealed, because static methods cannot be overridden either

28 2009 first semister Instructor: Abdalrahman Obidat 28 protected internal keyword protected members are visible to any subclass even if the subclass is not in the same assembly internal members are visible to any class within the same assembly C# offers the combination protected internal to mean visible to any subclass anywhere and to any class within the same assembly

29 2009 first semister Instructor: Abdalrahman Obidat 29 Visibility summary for class members ModifierVisibility private (or none) Class only internalAll classes within the same assembly protectedSubclasses anywhere protected internal Subclasses anywhere and all classes within the same assembly publicAll classes

30 2009 first semister Instructor: Abdalrahman Obidat 30 Abstract classes Some classes are so abstract that instances of them shouldn't even exist –What does it mean to have an instance of Animal ? An abstract class is one that should not or can not be instantiated.  A concrete class can have instances It may not make sense to attempt to fully implement all methods in an abstract class –What should Animal.speak() do?

31 2009 first semister Instructor: Abdalrahman Obidat 31 abstract keyword declare a method with the abstract modifier to indicate that it just a prototype. It is not implemented. It is implicitly marked virtual. It can't be marked private (since it must be overridden). public abstract void speak(); A class that contains an abstract method must be declared abstract public abstract class Animal{ public abstract void speak(); // more code }

32 2009 first semister Instructor: Abdalrahman Obidat 32 Using abstract classes An abstract class can't be instantiated. An abstract class can contain other non abstract methods and ordinary variables To use it, subclass it. Implement the abstract methods in the subclass If a subclass doesn't implement all of the base class abstract methods, the subclass is also abstract and must be declared as such. Abstract classes provides a framework to be filled in by the implementer

33 2009 first semister Instructor: Abdalrahman Obidat 33 Abstract class example public abstract class Accommodation{ protected boolean vacancy; protected int NumberOfRooms; public abstract void reserveRoom(); public abstract void checkIn(); // etc... } public class Motel: Accommodation{ //must implement all of the abstract //methods of Accommodation //(if we want the class to be instantiated) //code would follow }

34 2009 first semister Instructor: Abdalrahman Obidat 34 Interfaces An interface is a purely abstract class An interface specifies a set of methods or properties that a class must implement (unless the class is abstract) Style: an interface name starts with an I. Everything inside an interface is implicitly public and abstract. But it is an error to mark the interface members as such. public interface IDriveable{ bool startEngine(); void stopEngine(); bool turn(Direction dir); }

35 2009 first semister Instructor: Abdalrahman Obidat 35 Using interfaces (1) An interface defines some set of behavior for an object. Think of an interface as a badge that can be worn by a class to say "I can do that". public class Automobile: IDriveable { // implements the methods of Driveable public boolean startEngine() { if (notTooCold) engineRunning = true; // more code } // other methods }

36 2009 first semister Instructor: Abdalrahman Obidat 36 Using interfaces (2) Interface types act like class types. –Variables can be of an interface type –method parameters can be of an interface type –A method return type can be an interface type –Any object that implements the interface can fill that spot. A class can implement as many interfaces as desired public class C: Base, I1, I2, I3 { /* class code */} This is how C# deals with multiple inheritance (  C++)

37 2009 first semister Instructor: Abdalrahman Obidat 37 Using interfaces (3) An interface can't contain any field (  Java) An interface can inherit from any number of interfaces. public interface I: I1, I2, I3 {/*code*/} A concrete class that implements an interface must implement all of the methods in the interfaces of the hierarchy of that interface.

38 2009 first semister Instructor: Abdalrahman Obidat 38 Method Hiding class Super { public Super() {...}; public void DoSomething() {... } class Sub : Super { public Sub() {...}; public new void DoSomething() {... } (not virtual) This "hides" the method of the parent, making it inaccessible through the derived class. This applies to any class member. A compiler warning is given unless the new keyword is used. (not virtual)

39 2009 first semister Instructor: Abdalrahman Obidat 39 Method Hiding using System; using System.Collections; class Hello { static void Main() { Super super = new Super(); Sub sub = new Sub(); super.DoSomething(); sub.DoSomething(); } (cont. ->) class Super { public Super() {} public void DoSomething() { Console.WriteLine("Inside Super"); } class Sub : Super { public Sub() {} public new void DoSomething() { Console.WriteLine("Inside Sub"); }

40 2009 first semister Instructor: Abdalrahman Obidat 40 Method Hiding using System; using System.Collections; class Hello { static void Main() { Super super = new Super(); Sub sub = new Sub(); ArrayList arr = new ArrayList(); arr.Add(super); arr.Add(sub); ((Super) arr[0]).DoSomething(); ((Super) arr[1]).DoSomething(); super.DoSomething(); sub.DoSomething(); } (cont. ->) class Super { public Super() {} public void DoSomething() { Console.WriteLine("Inside Super"); } class Sub : Super { public Sub() {} public new void DoSomething() { Console.WriteLine("Inside Sub"); }

41 2009 first semister Instructor: Abdalrahman Obidat 41 Method Hiding using System; using System.Collections; class Hello { static void Main() { Super super = new Super(); Sub sub = new Sub(); ArrayList arr = new ArrayList(); arr.Add(super); arr.Add(sub); ((Super) arr[0]).DoSomething(); ((Super) arr[1]).DoSomething(); super.DoSomething(); sub.DoSomething(); } (cont. ->) class Super { public Super() {} public virtual void DoSomething() { Console.WriteLine("Inside Super"); } class Sub : Super { public Sub() {} public override void DoSomething() { Console.WriteLine("Inside Sub"); }

42 2009 first semister Instructor: Abdalrahman Obidat 42 Exceptions public void SomeMethod(...) { File file = new File("Readme.txt");. file.Close(); } What happens if an error occurs in here? What happens if the file doesn’t exist?

43 2009 first semister Instructor: Abdalrahman Obidat 43 Part of the exception hierarchy

44 2009 first semister Instructor: Abdalrahman Obidat 44 Exceptions: the general idea try { some code that might throw an exception more code } catch (most specific exception) { handle the exception } catch (less specific exception) { handle the exception } catch (any exception) { handle the exception } finally { do this no matter what } still more code

45 2009 first semister Instructor: Abdalrahman Obidat 45 try { some code that might throw an exception more code No exception thrown } catch (most specific exception) { handle the exception } catch (less specific exception) { handle the exception } catch (any exception) { handle the exception } finally { do this no matter what } still more code

46 2009 first semister Instructor: Abdalrahman Obidat 46 try { some code that might throw an exception more code } catch (most specific exception) { handle the exception } catch (less specific exception) { This exception thrown handle the exception } catch (any exception) { handle the exception } finally { do this no matter what } still more code

47 2009 first semister Instructor: Abdalrahman Obidat 47 try { some code that might throw an exception more code } catch (most specific exception) { handle the exception } catch (less specific exception) { This exception thrown handle the exception return; } catch (any exception) { handle the exception } finally { do this no matter what } still more code

48 2009 first semister Instructor: Abdalrahman Obidat 48 try { some code that might throw an exception more code } catch (most specific exception) { handle the exception } catch (less specific exception) { This exception thrown handle the exception throw; } catch (any exception) { handle the exception } finally { do this no matter what } still more code

49 2009 first semister Instructor: Abdalrahman Obidat 49 using System.IO; public void SomeMethod(...) { File file = null; try { file = new File("Readme.txt"); more code } catch (FileNotFoundException e) { Console.WriteLine("File " + e.FileName + " not found"); } catch (Exception e) { Console.WriteLine(e); } finally { if (file != null) file.Close(); }

50 2009 first semister Instructor: Abdalrahman Obidat 50 Exceptions In a catch block, you can: Rethrow the same exception, notifying code higher in the call stack Throw a different exception, giving additional information to code higher in the call stack Handle the exception and fall out the bottom of the catch block

51 2009 first semister Instructor: Abdalrahman Obidat 51 Exceptions Remember that: Exceptions are not always "errors" Exceptions are not always infrequent Sometimes it's best not to catch an exception where it occurs There is a performance hit for exceptions

52 2009 first semister Instructor: Abdalrahman Obidat 52 Exceptions public void SomeMethod(...) { File file = null; try { file = new File("Readme.txt"); more code } finally { if (file != null) file.Close(); } Since there is no catch block, the exception is propagated to the caller


Download ppt "2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat."

Similar presentations


Ads by Google