You are on page 1of 22

Object oriented programming languge : Traditional programming language like c, known as Structural programming language lacks the functionality

y code security and reusablility of code. To provide the security and reusability of code in new approach in programming has been introduced as object oriented programming A language to be called as object oriented need to satisfied a set of basic priniciples

Encapsulation, Abstraction Inheritance, Polymorphism Encapsulation : Acording to this the code in an object oriented language as to be wrapped under a container known as class, which provides security to the code,. Abstraction : Its an approach wh ich talks about hiding of the complexity by providing the user with a set of interfaces to consulme the functionalities Inheritance : Acording to this members of a class can be accessed by another class . If they have parent child relation ship which provides code- reusability. Polymorphism : Entities behaving in diff. ways depending up on the input they received is known as polymorphis

Members of a class :

As we were aware of a class is a

collection of members and these members can be variables types like

Fields,methods,constructors,properties, delegates, events, enumeration

Field Declaration class Rectangle { public int Width public int Height; }

Multiple field declaration class Rectangle { public int Width, Height; }

Methods : Methods consider as members of class gets defined only under the class, as per the rule of encapsulation . Methods of variables defined under a class were considered as members of a class, where members of class can be accessed only through object of a class

In a object or copy of a class has to be created first to access the class because we were aware that types can t be consumed directly

Ex: program p = new program() Or Program p P= new program();

You can create the object of a class any where under a class as well as can be created from other classes , but while creating under the same class we do it under the main as it was the main entry of a class Test the program Class Program { Void test(); { Console.writeline(First METHOD); }

Void test2(int x) { Console.writeline(Second Method , x); }

String test3() { Return Third Method;

String test4(string name) { Return hello + name; } Int math(int x, int y ref int z) { Z=x*y; Return x+y; Static void main(string[] args)

Program p = new program(); p.test2(10); console.writeline(p.test3()); console.writeline(p.test4(Raju); int prod=0; int sum=p.math(100,50,ref prod); console.writeline(um + + prod); console.writeline(sum + + prod); }}

A variable which is declared using ref key word its considered as a reference variable or a variable or pointer variable C -->> int *p C# ref int p

A reference variable in c# language will never disclose the address which gets stored in it as well it will not allow pointer arthematic.

We store the address of variable under reference variable to refer to address of variable we prefix with ref key word only C -- > int *p =&x; C# -- > ref int p = ref x;

Add a class in year project naming it has first cs & wrote following code Class program { Int x = 100; Static void main ( ) { First f ; // f is a variable F = new first ( ); // f is on object Console write line (f.x); Console readline ( ); } } The memory which is required for on object gets allocated only with the user new operator. First f ; F= new first( );

You can explicitly destroyed the object of a class by assigning the value null to once if it was destroyed you can never access members of the class To test this re write the code under main method of the class first under following. First f= niw first () ; Console write line (f.x); F= null; Console write line ( f.x); Console read line( ); First f= new firstd( ); F = null Wecan create multiple objects to a class each objects we create for the class will maintain a separate copy of its members where the modification made on the a vetiable of the object doesnt reflec to vatrable of the other object To test this re write the code under main methods of class first as following. First f1= new first (); Firstf2=new first(); Console write line(f1.x+ +f2.x); F1.x=500 Console write line (f1.x+ + f2.x); Console read line (); We can assign the object of a class to the variable of name class. Which converts the variable to a reference [ con be used as on objects] for in this case both the objects & reference the dome memory location because in this case new is used only for once. To test this re write the code under main methods of a class first as following First f1 = new first(); First f2 = f1; Console write the ( f1.x+ + f2.x); F1.x= 500; Console write line (f1.x+ + f2.x); Console read line (); When multiple objective are referring to the name memory, when use assigned null to an objects the other object can still consume the memory. But not the object for which null was assigned to test this re write the code under main method of a class first as following. First f1 = new first (); First f2 = f1; // object destroyed // invalid // f is an object // valid

F1 = null; Console write line (f2.x); Console write line (f1.x); Console read line (); What is the role of new operator in object creation? When we use the new operator for creating the object public class Geometry { // Unknown Shape public double CalculateArea() { return; } // Square public double CalculateArea(double side) { return side * side; } // Rectangle public double CalculateArea(double length, double height) { return length * height; } } public class Exercise { static int Main() { var geo = new Geometry(); System.Console.WriteLine("Geometric Shapes"); System.Console.WriteLine("Calculation of Areas"); System.Console.Write("Square: "); System.Console.WriteLine(geo.CalculateArea(26.38)); System.Console.Write("Rectangle: "); System.Console.WriteLine(geo.CalculateArea(39.17, 26.38)); return 0; } } public class BankAccount { private string customerName; private decimal originalDeposit; public void Initialize(string name, decimal deposit) { customerName = name; originalDeposit = deposit; } public void Show() { System.Console.WriteLine("Customer Account Information"); System.Console.Write("Customer Name: "); System.Console.WriteLine(customerName); // valid // in volid

System.Console.Write("Original Deposit: "); System.Console.WriteLine(originalDeposit); } } public class Exercise { static int Main() { BankAccount account = new BankAccount(); account.Initialize("Paul Motto", 450.00M); account.Show(); return 0; } } Class members : What ever we define under a class were known as class members like variable, fields, methods ,constructor ,properties ,enumerations

These members were categorized into two types. Instance Members or Non Static Static Members What are non static or instance members ? Members of a class which requires the object of a class for initialization or execution were known as non static members What are static members ? Instance variables vs static variables Members of the class which doesnot require object of the class for intitalization or execution were known as static members

A variable declared using static modifier or a declared under static block were known as static variable and rest of all are Instance

Ex: Int x=100; // Instance Statc inty=200; static Static voidmain() { Int z=300; // static

++ Instance variable gets initialized whenever the object of class gets created . So the minimum and maximum no. of times its gets initialized will be zero or {n} Where as a static variable gets initialized once the execution of a class starts. So the minimum and the maximum no. of times its gets initialized will be only and one

Note :Use instanacevariable if you want the variable accessable only to the single object. Use static variables if we want to to be accessable to all objects While refereeing to instancemembers of a class we use the object of the class where as while refgering to static members of the class we use name of the class class Program { int x = 100; static int y = 100; static void Main(string[] args) { Console.WriteLine(Program.y); Program p1 = new Program(); Console.WriteLine(p1.x); Console.ReadLine(); } }

Instance Methods VS static methods A method declared by using static modifier is a static method rest of all are Instance : While defining static methods we need to consider a rule I,e non static members can not be refer from static block directly. They can be only referred using the object of the class where as static members can be refered from non static blocks directly.

class Program { int x = 100; // instance variable static int y = 100; static void mul() { Program p1 = new Program(); Console.WriteLine(p1.x * y); } static void Main(string[] args) {

Program.mul(); Console.ReadLine();

What is constructor ? A constructor is a special method available in every class responsible the variable of a class or initializing

The name of constructor method is same as the class name. A constructor method never returns a value Without a constructor under a class a class can never execute If the programmers did not define a constructor under his class , while compiling the class the compiler takes the responsiblilty of defining the constructor under a class tomake the class to execute

class Program { Program() { Console.WriteLine("constructor"); } void show() { Console.WriteLine("Method"); } static void Main(string[] args) { Program p1 = new Program(); Program p2 = new Program(); Program p3 = p1; p1.show(); p2.show(); p3.show(); } }

# Creating the object of the class using new operator will call the constructor ,which will allocate the memory required for the object Constructor are of two types 1.Default or Zero argument Constructor 2. Parameterized constructors # A constructor doesnot take any input parameters is known as Default Construtor .This can be defined either by a programmer or will be defined by the compiler A constructor which takes input paratmeters is known as parameterized constructors. This can be defined only by a programmer

If the constructor is parameterized ,you need to send the value to the parameters while creating the object of the class ,because a constructor call should match the constructor siognature. class Program { Program() { Console.WriteLine("constructor"); } Program(int x) { Console.WriteLine("Constructor :" + x);

} void show() { Console.WriteLine("Method"); } static void Main(string[] args) { Program p1 = new Program(10); Program p2 = new Program(20);

} } Instance constructors VS static constructors A constructor declared using the static modifier is a static constructor , rest of all are instance constructor. Static constructor are responsible for initializing static variables and instance constructor responsible for initializing instance variables

A static constructor gets called one and only one in the execution of a class, when the class execution starts

Where as instance constructor gets called zero or n times I,e each time the object of the class get called

Note : The first block of the code which gets executed in a class is static constructor V v..imp

As we can pass parameters to an instance constructor it can not be done in the case of static constructors Because static constructors never takes parameters or cant beparaeterized

class Class1 { // static constructor static Class1() { Console.WriteLine("Static construcotr"); } Class1() { Console.WriteLine("Non- staic construcorr"); } static void Main() { Class1 c1 = new Class1(); // Class1 c2= new Class1(); Console.ReadLine();

Method overloading : Overloading is an approach which allows toprovide multiple behavior to amethods

class overloaddemo { public void show() { Console.WriteLine("First Method"); } public void show(int x) { Console.WriteLine(x);

} public void show(string s) { Console.WriteLine(s); } public void show(int x, string s) { Console.WriteLine(4); } public void show(string s, int x) { Console.WriteLine(5); } static void Main()

{ overloaddemo od = new overloaddemo(); od.show(); od.show(10); od.show(10, "Hello"); od.show("hellow", 10); Console.ReadLine(); } }

Constructor Overloading : As you overload the methods ,you canalso overlaoad constructor of a class

Note : If you want to define a parameterized constructor under a class a make a habit of defining a default construcotor under the clas A class can be defined with any no. of constructor

Inheritance As we were aware a class is a collection of memebres and these members can be consumed or re-used by other classes once we have parent child relationship between the classes

Note : The default scope for members of class in c# is private . Where private members of a class cant be acquired by the children or child class

Syntax : [modifiers]class<Children name : <parent name >

Ex ; Class class1 { <define Members> }

Class Class2:class1

{ <define members> } class parent { public parent() { Console.WriteLine("Parent constructor"); } public void show() { Console.WriteLine("Method one ");

} public void show1() { Console.WriteLine("Method Two"); }

Add a child class class child : parent { public child() { Console.WriteLine("Constructor child "); } public void show3() { Console.WriteLine("Method Three"); } static void Main() { child c2 = new child(); c2.show3(); c2.show(); c2.show1(); Console.ReadLine();

} } }

While using inheritance we need to consider the following Rules and Regulations :

1.

In inheritance , execution of a child class always starts with calling the parent class . Default constructor which should always accessible to the child class. If not accessible inheritance will not be allowed

2.

As we aware , child classes can be refer to parent class members where as parent class can never refer to child class members

To test this Write the following code Class c1 = new class() C1.show(); C1.show2(); C1.show3() // invalid Console.readline();

As we aware that object of a class can be assigned to its variable it can also be assigned to parent class variables , but in this case we cant refer to members of child class using parent reference To test this write the following code Class2 c2 = new class2() Class1 c1 =c2 C1.show(), c1.show2(); c1.show3() // Invalid console.readline();
As per the standards of Object oriented programming language we have two types of inheritance 1. 2. Single Inheritance Multiple Inheritance

If a class has only one immediate base class to it we called it as single inheritance

Class1class2class3 If a child class has more thatn one immediate base class to it we called as Multiple I nheritance

*** Classical object oriented programming language like c++ supported both single and multiple Inheritances where as in modern obect oriented programming language like JAVA & .NET supports only sngle inheritance through classs because multiple inheritance suffers from the drawback of ambiguity.

Test() Class1 Class3

test() class2

As we aware that exection of child class starts by calling the default constructor of the parent . In some cases parent class may not contain a default constructor in it. i.e it may contain parametrised in such situation it is the programmer responsibility to call the available constructor or parent from the child class constructor using the base keyword. Base keyword is used to referring to members or paent class from a child clas. To test this make the constructor , or parent classs1 as parameterized Public class(int x) { Console.writeline(x) } Now , under the main() of classs1 send vaue to parameters while creatint its object as following Cclass1 c1= new classs1(10)

Sometmes it shows an error .. To overcome this problem use the Base key word as follows Public class2() : base(20) { Console.writeline(class2 constructor); }

Inheritance Based Overloading : If a method is overloaded under a child class we called it as inheritance based overloading

Parent.cs Public void test()

Public void test(int x) Child .cs Public void test(string s) {} Add a parent class and find

Note : As we aware overloading allows to provide multiple be behavior to a method , we can add new behavior to the method using a child when the parent provided were not as per our requirement.

Method Overriding

** If a method of parent class was re-defined in the child class with the same signature we called it has method over-ridding.

Differnce between overloading and Overriding This allows defining multiple methods with in the same name by changing their signature This can be performed with in a class or with in a child class When performed under the child class does not require any permission from parent OVERLOADING This allows defining multiple methods with same name and SAME signature This can be performed only with in a child class To perform this we require on explicit permission from parent. OVERRIDING

How does a parent class give permission to the child class to override or re-define the method The parent class gives the permission to the child class to re-define the method by declaring the method as virtual . now the child class can override the method on optional basis using the override modifier

Ex : Loadparent.cs Public void test() Public virtual void test(int x) Child.cs

Public override void test(int x)

Note : when the method is overridden under the child class object of the chil class gives the preference to load method and invokes the method it has overhidden but not the virual method of parent In overriding approach parent class provides a method to the child to consume it directly or re-define it as per the requirements

Question : After overriding a method under a child class can we invoke the virtual method of a parent from the child class . Ans : yes, this can be done in two ways. Create the object of the parent class under the child class to invoke the virtual method To test this write the following code under the main() of child class

Loadparen p =new loadparent(); Loadchild c = new loadchild() p.test(10); c.test(10)

Method Hiding : Can we re-write a method under the child class without permission from parent ? Yes, we can rewrite a method under the child without the permission of parent also I,e not declared as virtual ), we called this as method Hiding .

Method overloadin and method hiding were similar type approaches . Where in the first casse we re-write a method under a child which is declared as virtual in parent where as In the second case we re-write a method under thechilld which we not declared as virtual in parent

In case of overriding we use the override modifier to re-write a method Where as in case of method hiding we use the new modifier for re-writing the method

Public void test()

Public new void test()

To test re-write the code in the child class Public new void test() {console.writeline(Mehtod5); }

Sealed class : Question : how can we restrict a class not to be inherited by any other class ? If you want to restrict a class not to be inherited by any other class it should be declared using the sealed modifier Ex : Sealed class class1 { } Class Testoverride: Testchild //> Invalid { } Question : can we restrict a method not to be orve ridden under a child class ? Yes, if you want to restrict a method not to be overridden by child class it should be declared as sealed but every method by default sealed unless it was decalred as virtual. L Question : if a method is decalred as virtual under parent can any class overwrite it. Yes. If a method is decalred as viratual in parent any child class as a right to over write it Class1 public virtual void test(); // parent class Class-2 public override void test(); // child1 class //sealed Class3 public override void test() // child2 class

Question : Can we restrict further overriding of a method at a child class which was declared as virtual in its parent. Yes, this can be performed by using sealed modifier on the method while overriding Ex : Public virtual void test() // parent class

Class2 public seal0ed override void test() // child class Class3 public override void test(); // invalid because declared as sealed in class2b

Abstracts Methods and Abstract Classes

A Method without any method body is known as an abstract method what it has only the signature of the method The class under which u define the abstract methods is known as abstract class

When we use an Abstract Class? We use abstract classes when we want multiple child class to implement a method with same signature irrespective of logic

Interface : In object oriented programming we can also declare abstract members under another container I, e interface a part from abstract classes But these interface can contiain only abstract members in it Class : Only non-abstract members Abstract Class Abstract + non abstract members Interface Only abstract members Note : As we aware that multiple inheritance is not supported through a class but it was still supported with interfaces I,e a class can have only one immediate base class to it but we can have multiple immediate interface are parent

Syntax ; Modifiers<interface><name> { Abstract members declaration> ]

Rules : An interface cant be declared with any variable Every member of interface by default public Every member declared in a interface by default abstract An interface can be inherited from another interface just like a class inheriting from another class Check the example

Ex

abstract class Program { public abstract void add(int x, int y); public void } sub( int a , int b);

** The approach of abstract method is a bit similar to method overriding where as in case of overriding the method declared as virtual in parent can be overridden by the child optimally. But in case of abstract methods the method declared as abstract in parent should be overridden by the child which is mandatory.

Abstract classes provides restriction based properties to the child classes I,e the chi ld class as to implement all the abstract methods in the parent if at all it wants to access the non abstract methods of parent Parent. Virtual

Override on child is options

But where as parent Abstract----override on child Mondtory Note : Abstract classes provide restriction based properties to the the childl classes it the child class as to implement all the abstract methods in the parent if at all it wants to access the non-abstract metjods of parent

Abstract Class == Non abstract methods + Absrtact Methods It implelmets all abstract methods of parent 2. Now we can consurme non-abstract methods of parent

Whey is it mst for child class to rovidce the implementation for all abstract methods of its parent

Ans ; we can never create the obj of a class which contains any abstract methods It it. So if the child class doesnot provide the implementation the abstract methods of parent get inherted to child classes and will not allow to create the object

Note : An abstract class is never user to it self it can be consumed only by the child class that to after providing the implementation from abstract methods of thet parent Method overloading Providing Multiple Behaviour to a method Method Overriding Changing the behavior of amethod under childl class with a permission from parent Method Hiding Changing the behavior of amethod under child class without a permission from parent

Check the programme Note : As we discusses objects of a abstract classes cant be created , But there reference cam be created with the help of their child class object using the reference all the non-abstract and abstract metjhods which were declared u nder it . To Test this re-write the code under the main() of child class as following 0 Properties When You want to provide access to values of a class out side of class this can be done in two ways . Public variables Properties In case of variables it access is provide the user has a change of getting as well as setting the value If the same access is provided through a property the can be restricted in three ways 1. 2. 3. Read write property : Which provide get and set access Read only property : Which provides only Get Acess Write only property : Which provides only set access

Syntax : [<mnodifier],<type><name> { Get{<statement>} Set{<statement>} } ** The code U write under the get block gets executed when u try to capture the value of property String str=Hellow Int len=str.lengthget ** When we try to assign a value to the property the code under set block will be executed. ** If a property defines both set and get block it it it is a Read write Property

In C++ and Java, when creating the member variables of a class, programmers usually "hide" these members in private sections (C++) or create them as private (Java). This technique makes sure that a member variable is not accessible outside of the class so that the clients of the class cannot directly influence the value of the member variable.

You might also like