5. OOP2003© 2003 Microsoft1OOPSWeek 4Lesson Objectives• Carrying out practical on Inheritance• Carrying out practical on Interface5. OOP2003© 2003 Microsoft2Objectives“Classes, objects and object-oriented programming (OOP) play afundamental role in .NET. C# features full support for the objectoriented programming paradigm…”• Designing your own classes• Destroying objects and garbage collection• Inheritance• InterfacesPart 1• Designing your own classes…5. OOP2003© … Continue reading “Carrying out practical on Inheritance | My Assignment Tutor”
5. OOP2003© 2003 Microsoft1OOPSWeek 4Lesson Objectives• Carrying out practical on Inheritance• Carrying out practical on Interface5. OOP2003© 2003 Microsoft2Objectives“Classes, objects and object-oriented programming (OOP) play afundamental role in .NET. C# features full support for the objectoriented programming paradigm…”• Designing your own classes• Destroying objects and garbage collection• Inheritance• InterfacesPart 1• Designing your own classes…5. OOP2003© 2003 Microsoft3Simple class members• C# supports standard fields, methods and constructors– with standard access control: public, private, protectedpublic class Person{ public string Name;public int Age;// fields public Person()// default constructor{ this.Name = “?”; this.Age = -1; }public Person(string name, int age){ this.Name = name; this.Age = age; }// parameterized ctor public override string ToString(){ return this.Name; }// method }//classBasic design rules• Provide constructor(s)• Omit default constructor for parameterized initialization• Override ToString, Equals and GetHashCode• Data hiding: “hide as many details as you can”– enable access when necessary via accessors and mutators– .NET provides a cleaner mechanism via properties…5. OOP2003© 2003 Microsoft4Properties• Goal:– to allow our class users to safely write code like this:– provides field-like access with method-like semantics…– … enabling access control, validation, data persistence,screen updating, etc. Person p;p = new Person(“joe hummel”, 40);p.Age = p.Age + 1; Observation• Read of value (“Get”) vs. Write of value (“Set”)Person p;p = new Person(“joe hummel”, 40);p.Age = p.Age + 1;Get ageSet age5. OOP2003© 2003 Microsoft5Property implementation• Implementation options:– read-only– write-only– read-writepublic class Person{private string m_Name;private int m_Age;…public string Name { get { … } }public int Age { get { … } set { … } }}read-onlyread-writeExample• Simplest implementation just reads / writes private field:public class Person{private string m_Name;private int m_Age;… public string Name{// Name property get { return this.m_Name; }} public int Age{// Age property get { return this.m_Age; }set { this.m_Age = value; }}}5. OOP2003© 2003 Microsoft6Indexers• Enable array-like access with method-like semantics– great for data structure classes, collections, etc.People p; // collection of Person objectsp = new People();p[0] = new Person(“joe hummel”, 40);. . .age = p[0].Age;SetGetExample• Implemented like properties, with Get and Set methods: public class People{private Person[] m_people; // underlying array…get { return this.m_people[i]; }set { this.m_people[i] = value; }}get { return …; }}} public Person this[int i] // int indexer{public Person this[string name] // string indexer{read-onlyread-write5. OOP2003© 2003 Microsoft7Part 2• Destroying objects and garbage collection…Object creation and destruction• Objects are explicitly created via new• Objects are never explicitly destroyed!– .NET relies upon garbage collection to destroy objects– garbage collector runs unpredictably…5. OOP2003© 2003 Microsoft8Finalization• Objects can be notified when they are garbage collected• Garbage collector (GC) will call object’s finalizerpublic class Person{…~Person() // finalizer{…}Should you rely upon finalization?• No!– it’s unpredictable– it’s expensive (.NET tracks object on special queue, etc.)• Alternatives?– design classes so that timely finalization is unnecessary– provide Close / Dispose method for class users to call** Warning **As a .NET programmer, you are responsible for calling Dispose / Close. Rule ofthumb: if you call Open, you need to call Close / Dispose for correct execution.Common examples are file I/O, database I/O, and XML processing.5. OOP2003© 2003 Microsoft9Part 3• Inheritance…Inheritance• Use in the small, when a derived class “is-a” base class– enables code reuse– enables design reuse & polymorphic programming• Example:– a Student is-a PersonUndergraduatePersonStudent EmployeeGraduate Staff Faculty5. OOP2003© 2003 Microsoft10Implementation• C# supports single inheritance– public inheritance only (C++ parlance)– base keyword gives you access to base class’s members public class Student : Person{private int m_ID;public Student(string name, int age, int id) // constructor:base(name, age){this.m_ID = id;}} StudentPersonBinding• C# supports both static and dynamic binding– determined by absence or presence of virtual keyword– derived class must acknowledge with new or overridepublic class Person{…// statically-boundpublic string HomeAddress(){ … }// dynamically-boundpublic virtual decimal Salary(){ … }}public class Student : Person{…public new string HomeAddress(){ … }public override decimal Salary(){ … }}5. OOP2003© 2003 Microsoft11All classes inherit from System.ObjectString Array ValueType Exception Delegate Class1MulticastDelegate Class2Class3ObjectEnum1Primitive types Enum Structure1BooleanByteInt16Int32Int64CharSingleDoubleDecimalDateTimeSystem-defined typesUser-defined typesDelegate1TimeSpanGuidPart 4• Interfaces…5. OOP2003© 2003 Microsoft12Interfaces• An interface represents a design• Example:– the design of an object for iterating across a data structure– interface = method signatures only, no implementation details!– this is how foreach loop works…public interface IEnumerator{ void Reset();bool MoveNext();object Current { get; }// reset iterator to beginning// advance to next element// retrieve current element }Why use interfaces?• Formalize system design before implementation– especially helpful for PITL (programming in the large)• Design by contract– interface represents contract between client and object• Decoupling– interface specifies interaction between class A and B– by decoupling A from B, A can easily interact with C, D, …5. OOP2003© 2003 Microsoft13.NET is heavily influenced by interfaces• IComparable• ICloneable• IDisposable• IEnumerable & IEnumerator• IList• ISerializable• IDBConnection, IDBCommand, IDataReader• etc.Example• Sorting– FCL contains methods that sort for you– sort any kind of object– object must implement IComparableobject[] students;students = new object[n];students[0] = new Student(…);students[1] = new Student(…);. . .Array.Sort(students);public interface IComparable{int CompareTo(object obj);}5. OOP2003© 2003 Microsoft14To be a sortable object…• Sortable objects must implement IComparable• Example:– Student objects sort by idpublic class Student : Person, IComparable{private int m_ID;…int IComparable.CompareTo(Object obj){Student other;other = (Student) obj;return this.m_ID – other.m_ID;}}base class interfaceStudentPersonSummary• Object-oriented programming is *the* paradigm of .NET• C# is a fully object-oriented programming language– fields, properties, indexers, methods, constructors– garbage collection– single inheritance– interfaces• Inheritance?– consider when class A “is-a” class B– but you only get single-inheritance, so make it count• Interfaces?– consider when class C interacts with classes D, E, F, …– a class can implement any number of interfaces5. OOP2003© 2003 Microsoft15References• Books:– I. Pohl, “C# by Dissection”– S. Lippman, “C# Primer”– J. Mayo, “C# Unleashed”