Subject Name C AND NET CONCEPTS Subject Code
Subject Name: C# AND. NET CONCEPTS Subject Code: 10 CS 761 Prepared By: Ms Suganthi S ( Asst. Professor), Dr Lokesh (Professor) Department: CSE Date : 22. 09. 2014 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 1
UNIT – IV OBJECT ORIENTED PROGRAMMING WITH C# 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 2
TOPIC DETAILS üDefinition of the C# Class üDefault Public Interface” of a Type üPillars of OOP üThe first Pillars: C#’s Encapsulation Services üPseudo-Encapsulation ücreating Read-only fields üthe second Pillar: C#’s Inheritance supports üthe “protected” keyword ünested types definition üThe third Pillar: C#’s Polymorphic support ücasting Between types 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 3
DEFINITION OF C# CLASS ØIt’s a building block that contains properties and functionalities that describe some group of objects ØCreating object of a specific class type called instance of the class ØIs a User Defined Type(UDT) that is composed of data and functions that act upon this data ØAccess specifiers specify the access rules for the members as well as the class itself, if not mentioned then the default access specifier for a class type is internal. Default access for the members is private ØData type specifies the type of variable, and return type specifies the data type of the data, the method returns, if any ØTo access the class members, you will use the dot (. ) operator ØThe dot operator links the name of an object with the name of a member 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 4
SYNTAX <access specifier> class_name { // member variables <access specifier> <data type> variable 1; <access specifier> <data type> variable 2; . . . <access specifier> <data type> variable. N; // member methods <access specifier> <return type> method 1(parameter_list) { // method body } <access specifier> <return type> method 2(parameter_list) { // method body }. . . <access specifier> <return type> method. N(parameter_list) { // method body }} 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 5
EXAMPLE using System; namespace Box. Application { class Box { public double length; // Length of a box public double breadth; // Breadth of a box public double height; // Height of a box } class Boxtester { 1/8/2022 static void Main(string[] args) { Box 1 = new Box(); // Declare Box 1 of type Box Box 2 = new Box(); // Declare Box 2 of type Box double volume = 0. 0; // Store the volume of a box here C#AND. NET 10 CS 761_UNIT IV // box 1 specification Box 1. height = 5. 0; Box 1. length = 6. 0; Box 1. breadth = 7. 0; 6
EXAMPLE(Contd…. . ) // box 2 specification Box 2. height = 10. 0; Box 2. length = 12. 0; Box 2. breadth = 13. 0; // volume of box 1 volume = Box 1. height * Box 1. length * Box 1. breadth; Console. Write. Line("Volume of Box 1 : {0}", volume); of Box 2 : {0}", volume); Console. Read. Key(); } } } OUTPUT: Volume of Box 1 : 210 Volume of Box 2 : 1560 // volume of box 2 volume = Box 2. height * Box 2. length * Box 2. breadth; Console. Write. Line("Volume 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 7
CONSTRUCTORS IN C# Ø A class constructor is a special member function of a class that is executed whenever we create new objects of that class Ø A constructor will have exact same name as the class and it does not have any return type Ø A default constructor does not have any parameter but if you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 8
EXAMPLE using System; return length; } namespace Line. Application static void Main(string[] args) { class Line { Line line = new Line(); { private double length; // set line length // Length of a line. set. Length(6. 0); public Line() Console. Write. Line("Length of line : {0}", {Console. Write. Line("Objectis being created"); line. get. Length()); } Console. Read. Key(); } } } public void set. Length( double len ) OUTPUT: { length = len; } Object is being created public double get. Length() Length of line : 6 { 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 9
DESTRUCTORS Ø A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope Ø A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters Ø Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc Ø Destructors cannot be inherited or overloaded 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 10
EXAMPLE using System; public double get. Length() namespace Line. Application { { return length; } class Line { private double length; static void Main(string[] args) // Length of a line { Line line = new Line(); // set line length public Line() // constructor line. set. Length(6. 0); { Console. Write. Line("Object is being created"); } Console. Write. Line("Length of line : {0}", line. get. Length()); } } } ~Line() //destructor OUTPUT { Console. Write. Line("Object is being deleted"); Object is being created } public void set. Length( double len ) Length of line : 6 { length = len; } Object is being deleted 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 11
PUBLIC INTERFACE Ø Public Interface is any item declared in a class using “public” keyword Ø Class members which are accessible from an object variable are called as public interface of a class Ø Public interface of a class is populated by 1. methods-member functions 2. properties- Accessors and mutators 3. public fields or public variables 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 12
PILLARS OF OOP Ø Encapsulation Ø Inheritance Ø Polymorphism 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 13
ENCAPSULATION Ø Procedure of covering up of data and functions into a single unit (called class) Ø An encapsulated object is often called an abstract data type NEED FOR ENCAPSULATION Ø Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways: Ø The first method is using a pair of conventional accessor and mutator methods Ø Another one method is using a named property 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 14
ENCAPSULATION USING ACCESSORS AND MUTATORS Ø To manipulate the data in that class (String departname) we define an accessor (get method) and mutator (set method) using system; public class Department { private string departname; . . . . // Accessor. public string Get. Departname() { return departname; } // Mutator. public void Set. Departname( string a) { departname=a; } } 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 15
Ø Here we use two separate methods to assign and get the required data public static int Main(string[] args) { Department d = new Department(); d. Set. Departname("ELECTRONICS"); Console. Write. Line("The Department is : "+d. Get. Departname()); return 0; } Ø In the above example we can't access the private data departname from an object instance. We manipulate the data only using those two methods 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 16
ENCAPSULATION USING PROPERTIES using system; public class Department { private string departname; public string Departname { get { return departname; } set { departname=value; } } } 1/8/2022 public class Departmentmain { public static int Main(string[] args) { Department d= new Department(); d. departname="Communication"; Console. Write. Line("The Department is {0}", d. Departname); return 0; } } C#AND. NET 10 CS 761_UNIT IV 17
Ø The property has two accessor get and set. The get accessor returns the value of the some property field. Ø The set accessor sets the value of the some property field with the contents of "value". Properties can be made read-only. Ø This is accomplished by having only a get accessor in the property implementation. 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 18
READ ONLY PROPERTY } using system; public class Read. Departmain public class Read. Department { { private string departname; public static int Main(string[] args) public Read. Department(string avalue { ) Read. Department { d= new Read. Department("COMPUT departname=avalue; ERSCIENCE"); } Console. Write. Line("The Department public string Departname is: {0}", d. Departname); { return 0; get } { } return departname; } } 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 19
Ø The class Read. Department has a Departname property that only implements a get accessor. Ø It leaves out the set accessor. This particular class has a constructor, which accepts a string parameter. Ø The Main method of the Read. Departmain class creates a new object named d. Ø The instantiation of the d object uses the constructor of the Read. Department that takes a string parameter. Ø Since the above program is read-only, we cannot set the value to the field departname and we only read or get the value of the data from the field. 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 20
WRITE ONLY PROPERTY Ø Properties can be made also Writeonly. This is accomplished by having only a set accessor in the property implementation. using system; public class Write. Department { private string departname; public string Departname { set { departname=value; Console. Write. Line("The Department is : {0}", departname); 1/8/2022 } } } public class Write. Departmain { public static int Main(string[] args) { Write. Department d= new Write. Department(); d. departname="COMPUTERSCIE NCE"; return 0; } } C#AND. NET 10 CS 761_UNIT IV 21
Ø The class Write. Department has now has a Departname property that only implements a set accessor. Ø It leaves out the get accessor. Ø The set accessor method is varied a little by it prints the value of the departname after it is assigned. 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 22
INHERITANCE Ø Reuse existing code Ø Relationship between 2 or more classes Ø All variables and methods in the base class can be called in the derived classes. Ø 2 flavors of inheritance 1. classical inheritance(“is-a” relationship) 2. containment/delegation model(“has-a” relationship) 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 23
CLASSICAL INHERITANCE Ø New classes may extend the functionality of other classes Ø Is-a relationship Ø Sales person “is-a” Employee 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 24
Ø Here base classes are used to define general characteristics that are common to all subclasses Using System; public class parentclass { public parentclass() { Console. Write. Line(“parent constructor”); } public void print() { Console. Write. Line(“I’m a parent class”); } } public class childclass: parentclass { 1/8/2022 public childclass() { Console. Write. Line(“child constructor”); } public static void Main() { Childclass c=new childclass(); c. print(); } } OUTPUT: Parent constructor child constructor I’m a parent class C#AND. NET 10 CS 761_UNIT IV 25
Containment/Delegation model public class car Ø Has-a relationship { Ø Specifies how one class is made up of other classes(the parts) public string make; public class engine public void start() { { public void start() engine. start(); { System. console. Write. Line(“ started”); public engine e; } Engine } }} 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 26
BASE KEYWORD Ø Used to access the members of base class from within a derived class 1. Call a method on the base class that has been overridden by another method 2. Specifies which base class constructor should be called when creating instances of the derived class 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 27
Using System; Class A { Public int i; Public a(int i) { This. i=i; } } Class B: A { New int i=0; Public B(int i): base(i) { This. i=100; } Public void display() { Console. Write. Line(“value of base 1/8/2022 class 1 is {0}, base, i); Console. Write. Line(“value of derived class 1 is {0}, i); } Static void Main() { B b=new B(10); b. display(); } } OUTPUT: Value of base class 1 is 10 Value of derived class 1 is 100 C#AND. NET 10 CS 761_UNIT IV 28
PREVENTING INHERITANCE: SEALED CLASS Ø When a class is declared with sealed keyword, it cannot be inherited Ø Error will occur if a sealed class is declared as base class of another class Ø It is used to prevent the derivation of a class Ø Structs are implicitly sealed. 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 29
SEALED METHODS Ø A method can’t be declared as sealed Ø When overriding a method in a derived class, the override method can be declared as sealed. Ø We can avoid further overriding of the method which is declared as sealed. 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 30
EXAMPLE Using System; Console. Write. Line(“sealed method”); Sealed class A } { public void display() pubic static void Main() { { Console. Write. Line(“virtual method”); B b=new B(); } b. display(); } } public class B: A } { public override sealed void display() { 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 31
PROTECTED KEYWORD Ø The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers Ø A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type class A { protected int x = 123; } class B : A { static void Main() { A a = new A(); B b = new B(); // Error CS 1540, because x can only be accessed by // classes derived from A. // a. x = 10; // OK, because this class derives from A. b. x = 10; } } 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 32
PROTECTED KEYWORD(CONTD. . ) Ø The statement a. x = 10 generates an error because it is made within the static method Main, and not an instance of class B Ø Struct members cannot be protected because the struct cannot be inherited. Ø In this example, the class Derived. Point is derived from Point. Therefore, you can access the protected members of the base class directly from the derived class Point { protected int x; protected int y; } class Derived. Point: Point { static void Main() { Derived. Point dpoint = new Derived. Point(); // Direct access to protected members: dpoint. x = 10; dpoint. y = 15; Console. Write. Line("x = {0}, y = {1}", dpoint. x, dpoint. y); } } // Output: x = 10, y = 15 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 33
POLYMORPHISM Ø Ø Polymorphism means having many forms one interface, multiple functions Polymorphism can be static or dynamic In static polymorphism the response to a function is determined at the compile time Ø In dynamic polymorphism , it is decided at run-time 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 34
DYNAMIC POLYMORPHISM using System; public class Drawing. Object { public virtual void Draw() { Console. Write. Line("I'm just a generic drawing object. "); }} public class Line : Drawing. Object { public override void Draw() { Console. Write. Line("I'm a Line. "); }} public class Circle : Drawing. Object { public override void Draw() { Console. Write. Line("I'm a Circle. "); }} public class Square : Drawing. Object { public override void Draw() { Console. Write. Line("I'm a Square. "); }} using System; public class Draw. Demo { public static int Main( ) { Drawing. Object[] d. Obj 1/8/2022 = new Drawing. Object[4]; d. Obj[0] = new Line(); d. Obj[1] = new Circle(); d. Obj[2] = new Square(); d. Obj[3] = new Drawing. Object(); foreach (Drawing. Object draw. Obj in d. Obj) { draw. Obj. Draw(); } return 0; }} OUTPUT: I'm a Line. I'm a Circle. I'm a Square. I'm just a generic drawing object. C#AND. NET 10 CS 761_UNIT IV 35
STATIC POLYMORPHISM Ø same function print() is being used to print different data types using System; namespace Polymorphism. Application { class Printdata { void print(int i) { Console. Write. Line("Printing int: {0}", i ); } void print(double f) { Console. Write. Line("Printing float: {0}" , f); } void print(string s) { Console. Write. Line("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p. print(5); 1/8/2022 // Call print to print float p. print(500. 263); // Call print to print string p. print("Hello C++"); Console. Read. Key(); }}} OUTPUT: Printing int: 5 Printing float: 500. 263 Printing string: Hello C++ C#AND. NET 10 CS 761_UNIT IV 36
ABSTRACT METHODS AND CLASSES Ø Must be Implemented in derived classes public abstract class shape { //class definition } Ø Abstract class cannot be instantiated Ø It provides common definition of base class that multiple derived classes can share Ø It contains 1 or more abstract methods or abstract properties such that they wont provide implementations, but derived classes must override inherited abstract methods or properties Ø Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return of the method 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 37
EXAMPLE public abstract class shape { public abstract void draw(); } Ø Abstract methods have no implementation Ø Derived classes of the abstract class must implement all the abstract methods 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 38
CASTING BETWEEN TYPES Ø Casting variables is not simple. A complicated set of rules resolves casts Ø In some cases data is lost and the cast cannot be reversed Ø In others an exception is provoked Ø Complex conversions are often required Different Types of Type Casting or Type Conversion Implicit conversion Ø is being done automatically by the compiler and no data will be lost. It includes conversion of a smaller data type to a larger data types and conversion of derived classes to base class. This is a safe type conversion Explicit conversion Ø Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 39
IMPLICIT CONVERSION int smallnum = 654667; // Implicit conversion long big. Num = smallnum; class Base { public int num 1 { get; set; } } class Derived : Base Ø If we try to assign a value from derived class to a base class it will { public int num 2 { get; set; } } work class Program { Ø that is because a derived class alwaysstatic void Main(string[] args) is-a base class { Derived d = new Derived(); Ø Also, from a memory perspective a //Implicit Conversion base class variable pointing to a derived class object can safely access. Base b = d; the base class part of the object in }} memory without any problem 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 40
EXPLICIT CONVERSION Ø Explicit casting actually tells the compiler that we know about possible information loss/mismatch but still we need to perform this cast Ø This is ok for inbuilt numeric types but in case of reference types, there is a possibility that the types are not at all compatible i. e. casting from one type to another is not at all possible Ø For example casting a string "abc" to Integer is not possible Ø Such casting expressions will compile successfully but they will fail at runtime. What C# compiler does it that it checks whether these two types are cast compatible or not and if not it raises an exception. Invalid. Cast. Exception 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 41
EXAMPLE long big. Num = 654667; // Explicit conversion int smallnum = (int)big. Num; class Base { public int num 1 { get; set; } } class Derived : Base { public int num 2 { get; set; } } 1/8/2022 class Program { static void Main(string[] args) { Base b = new Base(); //Explicit Conversion Derived d = (Derived)b; }} C#AND. NET 10 CS 761_UNIT IV 42
USER-DEFINED CONVERSION Ø User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 43
UPCASTING AND DOWNCASTING Ø Implicit conversion of derived classes class Program { Explicit conversion of base class to static void Main(string[] args) { derived classes is called Downcasting Derived d 1 = new Derived(); class Base //Upcasting { Base b 1 = d 1; public int num 1 { get; set; } } Base b 2 = new Base(); to base class is called Upcasting and class Derived : Base { public int num 2 { get; set; } } 1/8/2022 //Downcasting Derived d 2 = (Derived)b 2; } } C#AND. NET 10 CS 761_UNIT IV 44
'IS' AND 'AS' OPERATORS Ø whenever we are using explicit casts, it is always a good idea to wrap the cast inside a try-catch block. C# also provides is and as operators which are helpful in performing explicit casts in an exception safe manner Ø The is operator checks whether the type being casted from is compatible to the type being casted to and returns a boolean value 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 45
EXAMPLE static void Main(string[] args) { CASE 1 ***** // This will work fine as o 1 is actually an int object o 1 = 1; int i = (int)o 1; // CASE 2 ***** // This wont work because o 2 is not an int so we need // to have an is oprerator before the actual cast object o 2 = "1"; int j; if (o 2 is int) { j = (int)o 2; 1/8/2022 } // CASE 3 ***** // We can never know what is the atual type of // an object at runtime so its always better to use // is operator, rewriting the first case object o 3 = 1; int k; if (o 3 is int) { k = (int)o 3; } } C#AND. NET 10 CS 761_UNIT IV 46
Ø Case 1 in the above code snippet will throw an exception is o 1 is assigned to some type that is not int. the other 2 cases are exception safe and will only perform the cast if the types are compatible for casting Ø There is one small performance issue in using is operator. Case 3 in above code snippet will work fine but it involves accessing the object twice. Once for checking the compatibility i. e. the is operator and secondly to actually extracting out the value i. e. casting. can we not have something like - "Check the compatibility and if compatible perform the cast" in one single operation 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 47
QUESTION BANK 1. Breifly explain the two pillars of OOPS in C# 2. With an example, Explain Mutators and Accessors. 3. What is the name of master node in System object? Explain with an examples. 4. Explain four method parameter modifiers, with an example. 5. Write a C# program to arrange 5 names in ascending order. The names are obtained from the command line arguments. 6. Explain the functions of System. Object class. Give overrided definition for To. String() and Equals(). 7. Write a program in C# to read a jogged array and display the sum of all the elements of three inner array 8. Explain Casting. With Example 9. What is Inheritance in c# ? Explain with suitable Program 10. Explain Methods Abstract with c# Program 11. With Program explain Methods Overloading in C# 12. What is Sealed Class ? Give example for Sealed Class 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 48
THANK YOU 1/8/2022 C#AND. NET 10 CS 761_UNIT IV 49
- Slides: 49