Download presentation
Presentation is loading. Please wait.
1
Chapter - 4 OOP with C# S. Nandagopalan
2
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
3
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
4
Employee Class Employee attributes: methods: string fullname;
int empID; float currPay; methods: void GiveBonus(float amount); void DisplayStats(); S. Nandagopalan
5
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
6
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, F); e.GiveBonus(200); e.DisplayStats(); S. Nandagopalan
7
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
8
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
9
Examples Encapsulation Inheritance Polymorphism
DBReader f = new DBReader(); // details are hidden // 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
10
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
11
Example Accessor Mutator class Employee { } private string fullName;
public string GetName() { return fullName; } ………….. } Mutator public string SetName(string n) { fullName = n; } ……………. S. Nandagopalan
12
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
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
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
34
End of Chapter 4 S. Nandagopalan
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.