890 likes | 1.06k Views
Programming in C# Object-Oriented. CSE 668 Prof. Roger Crawfis. Key Object-Oriented Concepts. Objects, instances and classes Identity Every instance has a unique identity, regardless of its data Encapsulation Data and function are packaged together Information hiding
E N D
Programming in C#Object-Oriented CSE 668 Prof. Roger Crawfis
Key Object-Oriented Concepts • Objects, instances and classes • Identity • Every instance has a unique identity, regardless of its data • Encapsulation • Data and function are packaged together • Information hiding • An object is an abstraction • User should NOT know implementation details
Key Object-Oriented Concepts • Interfaces • A well-defined contract • A set of function members • Types • An object has a type, which specifies its interfaces and their implementations • Inheritance • Types are arranged in a hierarchy • Base/derived, superclass/subclass • Interface vs. implementation inheritance
Key Object-Oriented Concepts • Polymorphism • The ability to use an object without knowing its precise type • Three main kinds of polymorphism • Inheritance • Interfaces • Reflection • Dependencies • For reuse and to facilitate development, systems should be loosely coupled • Dependencies should be minimized
Programming in C#Inheritance and Polymorphism CSE 668 Prof. Roger Crawfis
C# Classes • Classes are used to accomplish: • Modularity: Scope for global (static) methods • Blueprints for generating objects or instances: • Per instance data and method signatures • Classes support • Data encapsulation - private data and implementation. • Inheritance - code reuse
Inheritance • Inheritance allows a software developer to derive a new class from an existing one. • The existing class is called the parent, super, or base class. • The derived class is called a child or subclass. • The child inherits characteristics of the parent. • Methods and data defined for the parent class. • The child has special rights to the parents methods and data. • Public access like any one else • Protected access available only to child classes (and their descendants). • The child has its own unique behaviors and data.
Animal Bird Inheritance • Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class. • Inheritance should create an is-arelationship, meaning the child is a more specific version of the parent.
Declaring a Derived Class • Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class contents }
Controlling Inheritance • A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member. • Variables and methods declared with private visibility are not accessible in the child class • However, a private data member defined in the parent class is still part of the state of a derived class. • Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation • There is a third visibility modifier that helps in inheritance situations: protected.
Dictionary - definition : int + PrintDefinitionMessage() : void Book # pages : int + GetNumberOfPages() : void The protected Modifier • Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class • + public • private • # protected
Single Inheritance • Some languages, e.g., C++, allowMultiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents. • C# and Java support single inheritance, meaning that a derived class can have only one parent class.
Overriding Methods • A child class can override the definition of an inherited method in favor of its own • That is, a child can redefine a method that it inherits from its parent • The new method must have the same signature as the parent's method, but can have a different implementation. • The type of the object executing the method determines which version of the method is invoked.
Class Hierarchies • A child class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat
Class Hierarchies CommunityMember Employee Student Alumnus Faculty Staff Under Graduate Professor Instructor
Class Hierarchies Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Cylinder
Class Hierarchies • An inherited member is continually passed down the line • Inheritance is transitive. • Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.
References and Inheritance • An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance. • For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object. Holiday day; day = new Holiday(); … day = new Christmas();
Dynamic Binding • A polymorphic reference is one which can refer to different types of objects at different times. It morphs! • The type of the actual instance, not the declared type, determines which method is invoked. • Polymorphic references are therefore resolved at run-time, not during compilation. • This is called dynamic binding.
Dynamic Binding • Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it). • Now consider the following invocation: day.Celebrate(); • If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version
Overriding Methods • C# requires that all class definitions communicate clearly their intentions. • The keywords virtual, override and new provide this communication. • If a base class method is going to be overridden it should be declared virtual. • A derived class would then indicate that it indeed does override the method with the override keyword.
Overriding Methods • If a derived class wishes to hide a method in the parent class, it will use the new keyword. • This should be avoided.
Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Example: intfoo(string[] bar); intfoo(int bar1, float a); Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overriding lets you define a similar operation in different ways for different object types Example: class Base { publicvirtualintfoo() {} } class Derived { publicoverrideintfoo() {}} Overloading vs. Overriding
StaffMember Volunteer Employee Executive # name : string # address : string # phone : string # socialSecurityNumber : String # payRate : double - bonus : double + ToString() : string + Pay() : double + Pay() : double + ToString() : string + Pay() : double + AwardBonus(execBonus : double) : void + Pay() : double Hourly - hoursWorked : int + AddHours(moreHours : int) : void + ToString() : string + Pay() : double Polymorphism via Inheritance
Widening and Narrowing • Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Holiday day = new Christmas(); • Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast: Christmas christ = new Christmas(); Holiday day = christ; Christmas christ2 = (Christmas)day;
Widening and Narrowing • Widening conversions are most common. • Used in polymorphism. • Note: Do not be confused with the term widening or narrowing and memory. Many books use short to long as a widening conversion. A long just happens to take-up more memory in this case. • More accurately, think in terms of sets: • The set of animals is greater than the set of parrots. • The set of whole numbers between 0-65535 (ushort) is greater (wider) than those from 0-255 (byte).
Type Unification • Everything in C# inherits from object • Similar to Java except includes value types. • Value types are still light-weight and handled specially by the CLI/CLR. • This provides a single base type for all instances of all types. • Called Type Unification
The System.Object Class • All classes in C# are derived from the Object class • if a class is not explicitly defined to be the child of an existing class, it is a direct descendant of the Object class • The Object class is therefore the ultimate root of all class hierarchies. • The Object class defines methods that will be shared by all objects in C#, e.g., • ToString: converts an object to a string representation • Equals: checks if two objects are the same • GetType: returns the type of a type of object • A class can override a method defined in Object to have a different behavior, e.g., • String class overrides the Equals method to compare the content of two strings
Programming in C#Properties CSE 668 Prof. Roger Crawfis
Properties • Typical pattern for accessing fields. private int x; public int GetX(); public void SetX(int newVal); • Elevated into the language: privateint count; publicint Count {get { return count; }set { count = value; }} • Typically there is a backing-store, but not always.
Properties • Using a property is more like using a public field than calling a function: FooClass foo; int count = foo.Count; // calls get int count = foo.count; // compile error • The compiler automatically generates the routine or in-lines the code.
Properties • Properties can be used in interfaces • Can have three types of a property • read-write, read-only, write-only • More important with WPF and declarative programming. // read-only property declaration // in an interface. int ID { get; };
Automatic Properties • C# 3.0 added a shortcut version for the common case (or rapid prototyping) where my get and set just read and wrote to a backing store data element. • Avoids having to declare the backing store. The compiler generates it for you implicitly. publicdecimal CurrentPrice { get; set; }
Programming in C#Interfaces CSE 668 Prof. Roger Crawfis
Interfaces • An interface defines a contract • An interface is a type • Contain definitions for methods, properties, indexers, and/or events • Any class or struct implementing an interface must support all parts of the contract • Interfaces provide no implementation • When a class or struct implements an interface it must provide the implementations
Interfaces • Interfaces provide polymorphism • Many classes and structs may implement a particular interface. • Hence, can use an instance of any one of these to satisfy a contract. • Interfaces may be implemented either: • Implicitly – contain methods with the same signature. The most common approach. • Explicitly – contain methods that are explicitly labeled to handle the contract.
Interfaces Example public interface IDelete { void Delete(); } public class TextBox : IDelete { public void Delete() { ... } } public class Car : IDelete { public void Delete() { ... } } TextBox tb = new TextBox(); tb.Delete(); Car c = new Car(); iDel = c; iDel.Delete();
Explicit Interfaces • Explicit interfaces require the user of the class to explicitly indicate that it wants to use the contract. • Note: Most books seem to describe this as a namespace conflict solution problem. If that is the problem you have an extremely poor software design. The differences and when you want to use them are more subtle.
Explicit Interfaces namespace OhioState.CSE494R.InterfaceTest { publicinterfaceIDelete { void Delete(); } publicclassTextBox : IDelete { #regionIDelete Members voidIDelete.Delete() { ... } #endregion } } TextBox tb = new TextBox(); tb.Delete(); // compile error iDel = tb; iDel.Delete();
Explicit Interfaces • The ReadOnlyCollection<T> class is a good example of using an explicit interface implementation to hide the methods of the IList<T> interface that allow modifications to the collection. • Calling Add() will result in a compiler error if the type is ReadOnlyCollection. • Calling IList.Add() will throw a run-time exception .
Interfaces Multiple Inheritance • Classes and structs can inherit from multiple interfaces • Interfaces can inherit from multiple interfaces interface IControl { void Paint();} interface IListBox: IControl { void SetItems(string[] items);} interface IComboBox: ITextBox, IListBox { }
Programming in C#Structs CSE 668 Prof. Roger Crawfis
Classes vs. Structs • Both are user-defined types • Both can implement multiple interfaces • Both can contain • Data • Fields, constants, events, arrays • Functions • Methods, properties, indexers, operators, constructors • Type definitions • Classes, structs, enums, interfaces, delegates
C# Structs vs. C++ Structs • Very different from C++ struct
Class Definition public class Car : Vehicle { public enum Make { GM, Honda, BMW } private Make make; private string vid; private Point location; Car(Make make, string vid, Point loc) { this.make = make; this.vid = vid; this.location = loc; } public void Drive() { Console.WriteLine(“vroom”); } } Car c = new Car(Car.Make.BMW, “JF3559QT98”, new Point(3,7)); c.Drive();
Struct Definition public struct Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point p = new Point(2,5); p.X += 100; int px = p.X; // px = 102
Programming in C#Modifiers CSE 668 Prof. Roger Crawfis
Static vs. Instance Members • By default, members are per instance • Each instance gets its own fields • Methods apply to a specific instance • Static members are per type • Static methods can’t access instance data • No this variable in static methods