Chapter - 4 OOP with C# S. Nandagopalan.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
An Object-Oriented Approach to Programming Logic and Design
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Object Oriented Programming with C# Session: August-December 2009 Subject: C# Programming.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Polymorphic support in C# Let us now examine third pillar of OOP i.e. Polymorphism.. Recall that the Employee base class defined a method named GiveBonus(),
Programming using C# for Teachers Introduction to Objects Reference Types Functions of Classes Attributes and Types to a class LECTURE 2.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming in Java CSCI-2220 Object Oriented Programming.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Introduction to Object-Oriented Programming Lesson 2.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
OOP: Encapsulation &Abstraction
Classes (Part 1) Lecture 3
Static data members Constructors and Destructors
Object-Oriented Programming: Classes and Objects
Objects as a programming concept
7. Inheritance and Polymorphism
Final and Abstract Classes
Inheritance and Polymorphism
Microsoft Visual Basic 2005: Reloaded Second Edition
Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object-Oriented Programming: Classes and Objects
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Analysis and Design
OOP’S Concepts in C#.Net
The University of Texas Rio Grande Valley
Inheritance Basics Programming with Inheritance
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
Computer Programming with JAVA
Inheritance Inheritance is a fundamental Object Oriented concept
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Java Programming, Second Edition
Object-Oriented Programming: Classes and Objects
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Object-Oriented Programming: Inheritance and Polymorphism
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look UTPA – Fall 2012 This set of slides is revised from lecture.
Fundaments of Game Design
Inheritance.
CIS 199 Final Review.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
C++ Object Oriented 1.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Chapter - 4 OOP with C# S. Nandagopalan

Objectives Basic Class in C# Visibility Encapsulation Inheritance Accessor (get) and Mutator (set) Named Property Inheritance Sealed classes Polymorphism Abstract Class and Method S. Nandagopalan

C# Classes A Class is a custom User Defined Type (UDT) A Class consists of data (attributes) and functions (methods) Example: To model a generic Employee, we can define an Employee Class S. Nandagopalan

Employee Class Employee attributes: methods: string fullname; int empID; float currPay; methods: void GiveBonus(float amount); void DisplayStats(); S. Nandagopalan

Source Code using System; namespace Employee { public class Employee // private data private string fullName; private int empID; private float currPay; // Default ctor. public Employee(){ } // Custom ctor public Employee(string fullName, int empID, float currPay) // Assign internal state data. Note use of 'this' keyword this.fullName = fullName; this.empID = empID; this.currPay = currPay; } S. Nandagopalan

Source Code (Contd…) // Bump the pay for this emp. public void GiveBonus(float amount) {currPay += amount;} // Show the state public void DisplayStats() { Console.WriteLine("Name: {0}", fullName); Console.WriteLine("Pay: {0}", currPay); Console.WriteLine("ID: {0}", empID); } public static void Main(string[ ] args) Employee e = new Employee("Joe",111,23987.50F); e.GiveBonus(200); e.DisplayStats(); S. Nandagopalan

Method Overloading and 'this' Overloading of Methods is same as C++. Constructors can be overloaded. For method resolution, return type alone is not necessary! Is the keyword 'this' always necessary? Yes, if the parameter name and the class member name are same. Otherwise No! Static member functions can't use 'this' keyword. Why? The keyword 'this' can also be used to force one constructor to call another during the object creation Ex: public Employee(string fullName) : this(fullName, GetEmpId(), currPay) { } S. Nandagopalan

Basic OOP Concepts Encapsulation Inheritance Polymorphism Hiding unnecessary implementation details Inheritance "is-a" and "has-a" relationship "is-a" means sub-classes or derived classes "has-a" means containment or delegation Polymorphism It is the ability of the language to treat related objects the same way When sub-classes override the behavior defined by base a class, they are essentially redefining how they respond to the same message S. Nandagopalan

Examples Encapsulation Inheritance Polymorphism DBReader f = new DBReader(); // details are hidden f.Open("@C:\foo.mdf"); // process the database file f.Close(); Inheritance Polymorphism is-a Relationship Object Shape Hexagon has-a Relationship Car Radio Shape void Draw( ) Hexagon Circle Draw() S. Nandagopalan

More Details: (1) Encapsulation The main objective of encapsulation is: the object's instance should be allowed to access the internal member data directly. It also provides the integrity of state data. How to do this? Using private, public, protected, and protected internal keywords To manipulate the private data, C# provides two methods: Define traditional accessor and mutator methods Define a named property S. Nandagopalan

Example Accessor Mutator class Employee { } private string fullName; public string GetName() { return fullName; } ………….. } Mutator public string SetName(string n) { fullName = n; } ……………. S. Nandagopalan

Class Properties You can define a named property to avoid using two different get and set methods The property is a single named field which wraps the private data. These property names can then be used in Main( ). Ex: Assume EmpID is the name of the property public static void Main() { Employee e = new Employee(); p.EmpID = 111; // set Console.WriteLine(e.EmpID); // get } S. Nandagopalan

C# get and set Methods get block – accessor set block – mutator using System; namespace get_set { class MyClass private int a; public int A // property get // accessor return a; } set // mutator a = value; class Class1 { static void Main(string[] args) MyClass obj = new MyClass(); obj.A = 20; Console.WriteLine(obj.A); } get block – accessor set block – mutator A – named property S. Nandagopalan

Read-Only and Write-Only Properties The named property A in the previous slide was able to read and write. How to restrict the access of A as R/W? For Read-Only: simply define a property without a set block For write-only: simply define a property without a get block Ex: public float Pay public float Pay { { get { return currPay; } set { currPay = value; } } } S. Nandagopalan

static: properties and constructors The static keyword can be used for properties also The only difference is that, now these properties are bound to a class and not to an instance Ex: Employee.EmpID = 111; Can a constructor be declared as static? Yes, but it is strange! Why? Because, constructors are executed during object creation Static constructors are used to initialize static data S. Nandagopalan

Example – static property public class Employee { private static string companyName; public static string Company get { return companyName; } set {companyName = value; } } public static void Main(string[ ] args) Employee.Company = "Microsoft"; Console.WriteLine("The name is {0}", Employee. Company); S. Nandagopalan

Example – static constructor public class Employee { private static string companyName; static Employee() { companyName = "Microsoft"; } } public static void Main(string[ ] args) // below statement is not needed // Employee.Company = "Microsoft"; Console.WriteLine("The name is {0}", Employee.Company); S. Nandagopalan

Read-Only Fields Read-Only properties provide data preservation: keyword to be used is: "readonly" Ex: public readonly int rofield; You can't assign any value to the readonly fields, except in a constructor Ex: void SomeMethod() { rofield = 123; } // Error Static readonly fields can also be used. It is useful to associate many constant values bound to a class. It may be look similar to 'const' declaration. The difference, however, is that const is resolved at compile-time and static readonly is resolved at run-time. The other context in which it is valid to pass a readonly field as an out or ref parameter. S. Nandagopalan

More Details: (2) Inheritance Inheritance facilitates code reuse Inheritance provides dependency between types Inheritance comes in two flavors: "is-a" relationship "has-a" relationship Let us start with "is-a" relationship…… Employee Manager SalesPerson S. Nandagopalan

Manager – Derived Class using System; namespace Employee { public class Manager : Employee private ulong numberOfOptions; public ulong NumberOpts get { return numberOfOptions; } set { numberOfOptions = value; } } S. Nandagopalan

SalesPerson – Derived Class using System; namespace Employee { public class SalesPerson : Employee private int numerOfSales; public int NumbSales get { return numerOfSales; } set { numerOfSales = value; } } S. Nandagopalan

Base class and Subclass Constructors A subclass constructor automatically calls the base class constructor, by default Example: public Manager(string fullName, int empID, float currPay, ulong numberOfOpts) : base (fullName, empID, currPay) { numberOfOptions = numberOfOpts; } Refer to: Inheritance project folder for the complete source code S. Nandagopalan

More features of "is-a" Multiple Inheritance "protected " Keyword In C#, a given class can have exactly one direct base class It is not permitted to have a single type with one or more base classes "protected " Keyword You know that a private member can't be accessed by even subclasses "protected " data or methods can be accessed by subclasses Sealed Classes If you want to design a class that can't be inherited, then use the keyword: "sealed " A sealed class cannot also be an abstract class. It also enables certain run-time optimizations S. Nandagopalan

Example – Sealed Classes Employee Manager SalesPerson PTSalesPerson Add a subclass PTSalesPerson for SalesPerson class to have part – time sales people. Since we can't think of more child classes under PTSalesPerson, we shall seal it Sealed classes are most useful for designing standalone classes. Ex: String class in the System namespace Example public sealed PTSalesPerson : SalesPerson { ………. } S. Nandagopalan

Containment/Delegation or has-a relationship Let us consider two classes: A Car class and a Radio class It is odd to think of Radio is a Car! Instead, we can say a Car has a Radio Car – is called as Containing Class Radio – is called as Contained Class To expose the functionality of the inner class to the outside world requires delegation Delegation means adding members to the containing class that make use of the contained class's functionality (Ex: theMusicBox.TurnOn(state); ) Refer to: Containment folder for the complete source code S. Nandagopalan

More Details: (3) Polymorphism Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides. For Example, assume that you have added a new method to Employee class as: public void GiveBonus(float amount) { currPay += amount; } This method is common for all objects derived from Employee. However, our objective is to design this to behave differently for Manager and SalesPerson. This means that the subclasses should be able to provide different interfaces to Employee class Polymorphism is achieved through " virtual " and " override " keywords S. Nandagopalan

Types of Polymorphism Interface polymorphism - Multiple classes may implement the same interface, and a single class may implement one or more interfaces. Interfaces are essentially definitions of how a class needs to respond. An interface describes the methods, properties, and events that a class needs to implement. Inheritance polymorphism - Multiple classes may inherit from a single base class. By inheriting, a class receives all of the methods, properties, and events of the base class in the same implementation as the base class. Polymorphism through abstract classes - Abstract classes provide elements of both inheritance and interfaces. An abstract class is a class that cannot be instantiated itself; it must be inherited. S. Nandagopalan

Example public class Employee Base Claass { public virtual void GiveBonus(float amount) { currPay += amount; } ……… } public class SalesPerson : Employee public override void GiveBonus(float amount) int salesBonus = 0; if (numberOfSales > 200) salesBonus = 1000; base.GiveBonus(amount + salesBonus); You can reuse the base class method by using the keyword base Alternatively, the subclass can completely redefine without calling the base class method S. Nandagopalan

Abstract Classes An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class An abstract class is permitted (but not required) to contain abstract members An abstract class cannot be sealed – Why? Ex: If the Employee class is declared as abstract, the the following stmt. gives an error: Employee e = new Employee(); What is the need for an abstract class? Does it look OK if some one says "I am an Employee"? or "I am a Sales Person" S. Nandagopalan

Example A B C The abstract class A introduces an abstract method F. { public abstract void F(); } abstract class B: A public void G() {} class C: B public override void F() { // actual implementation of F } The abstract class A introduces an abstract method F. Class B introduces an additional method G, but since it doesn't provide an implementation of F, B must also be declared abstract. Class C overrides F and provides an actual implementation. Since there are no abstract members in C, C is permitted (but not required) to be non-abstract. A B C S. Nandagopalan

Shape Class – Design overview Same as pure virtual function of C++ The subclass Circle does not override Draw(), whereas Hexagon does Refer to Shapes Project public abstract class Shape { public virtual void Draw() { … } } It is more intelligent to declare Draw() as abstract public class Circle : Shape { … } public class Hexagon : Shape { public override void Draw() { ... } } S. Nandagopalan

Method Hiding Method hiding is opposite of Method overriding Assume that Oval is-a type of Circle. Of course you can define a method Draw() which overrides Draw() of its parent class and provide its own versioning. However, if we want to prevent the Oval class from inheriting any previous logic, use "new" keyword public class Oval : Circle { public Oval(){base.PetName = "Joe";} // Hide base class impl if they create an Oval. new public void Draw() Console.WriteLine("Oval with class versioning"); } new keyword breaks the relationship between base class of abstract Draw() and the derived class version S. Nandagopalan

new Modifier // The new modifier using System; public class MyBaseC { public static int x = 55; public static int y = 22; } public class MyDerivedC : MyBaseC new public static int x = 100; // Name hiding public static void Main( ) Console.WriteLine(x); // Display the overlapping value of x: Console.WriteLine(MyBaseC.x); // Access the hidden value of x: Console.WriteLine(y); // Display the unhidden member y: Output: 100 55 22 S. Nandagopalan

End of Chapter 4 S. Nandagopalan