Upload
gajendra-singh
View
214
Download
1
Embed Size (px)
DESCRIPTION
C# Inheritance
Citation preview
INHERITANCEand
POLYMORPHISM
Inheritance represents a kind of relationship between two classes .
Single inheritance(only one base class)Multiple inheritance(several classes)Hierarchical inheritance(one base class, many subclasses)Multilevel inheritance(derived from a derived class)
Note:C# does not directly implement multiple inheritance .
INHERITANCE
CONTAINMENT INHERITANCE
class A{……..…….}class B{……..A a; //a is contained in b}B b;
DEFINING SUB CLASS
A subclass is defined as follows:syntaxclass subclass-name:baseclass-name{variables declaration;methods declaration;}
using System;class item //base class{ public void company() { Console.WriteLine("itemcode=a12"); }}class fan : item{ public void model() { Console.WriteLine("fan model:"); Console.ReadLine(); }}class simpleinheritance{ public static void Main() { item i1=new item(); fan f1=new fan(); i1.company(); f1.company(); f1.model(); }}
Example of simple inheritance
VISIBILITY CONTROL
A class can have one of the visibility modifiers :public internalBy default the visibility modifier of class is internal.
Internal classes are accessible within the program assembly and are not accessible from outside the assembly.
A class members can have any one of the five visibility modifiers:publicprotectedprivateinternalprotected internal
Keyword Containingclasses
Derived Classes
Containing program
Anywhere Outside The Containing Program
private Yes
protected Yes Yes
internal Yes Yes Yes
protected internal
Yes Yes Yes
public Yes Yes Yes Yes
VISIBILITY
VISIBILITY OF CLASS MEMBERS
using System;class A{ private int x; protected int y; public int z; protected internal int s; internal int i;}class B:A{ A a1 = new A(); public void setxyz() { //x=10; y=20; z=30; s = 23; i = 34//Console.WriteLine("the value of private "+x); //errorConsole.WriteLine("the value of protected "+y);Console.WriteLine("the value of public "+z); Console.WriteLine("the value of protect internal "+s); Console.WriteLine("the value of internal " + i); Console.ReadLine(); }
class Main1 { public static void Main() { A a1 = new A(); // a1.y; //error B b1 = new B(); b1.setxyz();Console.WriteLine("the value of protected yin base class"+ b1.y); Console.ReadLine(); } } }
Member Modifier
Modifier of the Containing Classpublic internal private
public Everywhere Only program Only class
internal Only program Only program Only class
Private Only class Only class Only class
Accessibility domain of class Members
Accessibility Constraint
The direct base class of a derived class must be at least accessible as the derived class itself.
Accessibility domain of a member is never larger than that of class containing it.
The return type of method must be at least accessible as the method itself.
using System; class A{ private int x; protected int y; public int z; protected internal int s; internal int i;}public class B:A{ A a1 = new A(); public void setxyz() { //x=10; y=20; z=30; s = 23; i = 34;
ErrorInconsistent accessibility: base class 'A' is less accessible than class 'B‘Coz A is internal by default
Inconsistent accessibility:
//this is legalusing System;public class A{ private int x;}class B:A{ A a1 = new A(); public void setxyz() {}}
Accessibility domain of a member is never larger than that of class containing it.
class A{private class B{public int a;}}
Explanation:a is not accessible outside the class B, coz B is private ,the public on a is reduced to private.
Accessibility Constraint
The return type of method must be at least accessible as the method itself.
class A{private class B{A method1(){}internal A method2(){}public A method3(){} ///error
}}
Explanation:In the above example all the three methods in class B specify A as their return type. .Since the class A , by default is internal as accessibility level,public A method3() is an errorThe method cannot have an accessibility level higher than that of its return type.
Accessibility Constraint
Base
Base is used in constructors. A derived class constructor is required to call the constructor from its base class. When the default constructor isn't present, the custom base constructor can be referenced with the base keyword, directly in the constructor signature. This prevents derived classes from causing a compile-time error.
The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method.Specify which base-class constructor should be called when creating instances of the derived class.A base class access is permitted only in a constructor, an instance method, or an instance property accessor.It is an error to use the base keyword from within a static method.
To Pass Values to Base Class Constructor in single inheritance
using System;class base1{ public int length; public int breadth; public base1(int x, int y) { length = x; breadth = y; } public int area() { return (length * breadth); }}class derv1:base1{ int height; public derv1(int x,int y, int z):base(x,y) { height=z; }
public int volume() { return(length*breadth*height); }}class inhertest{ public static void Main() { derv1 d1 = new derv1(12,13,14); int area1=d1.area(); int vol1=d1.volume(); Console.WriteLine("area="+area1); Console.WriteLine("volume="+vol1); Console.ReadLine(); }}
To Pass Values to Base Class Constructor
using System;class base1{ public int length; public int breadth; public base1(int x, int y) { length = x; breadth = y; } public int area() { return (length * breadth); }}class derv1:base1{ int height; public derv1(int x,int y, int z):base(x,y) { height=z; }
public int volume() { return(length*breadth*height); }}class derv2:base1 { public derv2(int x, int y) : base(x, y) { } public int area2() { return(length*breadth); }}
To Pass Values to Base Class Constructor Example Continue
class inhertest{ public static void Main() { derv1 d1 = new derv1(12,13,14); derv2 d2 = new derv2(10,12); int a2=d2.area2(); int area1=d1.area(); int vol1=d1.volume(); Console.WriteLine("area="+area1); Console.WriteLine("volume="+vol1); Console.WriteLine("area="+a2); Console.ReadLine(); }}
Constructor
Use of keyword base is also used in any subclass to access a public or protected member defined in a parent class.
base.length=123;int area=base.Area();
are valid statement in the derived class
Usage of base Keyword
MULTILEVEL INHERITANCEclass A{protected int a;public A(int x){a=x;Console.WriteLine("in A" + a);}}class B:A{protected int b;public B(int x,int y):base(x){b=y;Console.WriteLine("in B" + y); }}class C:B{int c;public C(intx, int y, int z):base(x,y){c=z;Console.WriteLine("in C" + z);
}}
Note:The constructors are implemented in the following order.in A12in B13in C14
class inhertest { public static void Main() { C d1 = new C(12, 13, 14); Console.ReadLine();
} }}
OVERRIDING METHODSCreating a method in derived class with same signature as a method in base class is called as method overriding.Same signature means methods must have same name, same number of arguments and same type of arguments.
Method overriding is possible only in derived classes, but not within the same class.
When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.
To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.
OVERRIDING METHODS
If both sub class and super class has same method name ,same signatures .And we want to hide the base class method from the subclass (overriding a base class method) ,we declared base class method as virtual and the subclass method with the keyword override.
OVERRIDING METHODS
class super{ protected int x; public super(int x) { this.x=x; } public virtual void display() { Console.WriteLine("Super1Sx="+x); }}class sub :super{ int y; public sub(int x, int y):base(x) { this.y = y; }
public override void display(){ Console.WriteLine("Super x="+x); Console.WriteLine("Sub y="+y); //base.display(); Console.ReadLine();
} class overridetest { public static void Main() { sub s1= new sub(100,20); s1.display(); } }}
OVERRIDING METHODS
An override declaration may include the abstract modifier.It is an error for an override declaration to include new or static or virtual modifier.
The overridden base method cannot be static or non virtual.
The overridden base method cannot be sealed method.You cannot use the following modifiers to modify an override method: new static virtual abstract
OVERRIDING METHODS implementing abstract method
using System;namespace methodoverridingexample{ abstract class BaseClass { public abstract string YourCity(); }
class DerivedClass : BaseClass { public override string YourCity() //It is mandatory to implement absract method { return “Patiala"; }
OVERRIDING METHODS implementing abstract method continue
private int sum(int a, int b) { return a + b; } } class Program { static void Main(string[] args) { DerivedClass obj = new DerivedClass(); string city = obj.YourCity(); Console.WriteLine(city); Console.Read(); } }}OutputPatiala
HIDING METHODS
How do we override method without declaring as Virtual?
In C# we can use new modifier to tell the compiler that the derived class method “hides” the base class method.
The new modifier indicates that the method in derived class is ‘new’ , and it is intended to hide the inherited member.If the new modifier is used in a declaration of a member that does not hide any inherited member, then compiler will issue a warning.Can’t use both override and new modifiers in the same declaration.
HIDING METHODS New Modifier
class base1{ public void display() { Console.WriteLine("Base Method"); }}class derived1 : base1{ public new void display() { Console.WriteLine("Derived Method"); Console.ReadLine(); }}class newtest{ public static void Main() { derived1 d = new derived1(); d.display(); }}
A declaration of new method hides an inherited method only within the scope of the new method.
class A{public static void F(){}}class B:A{ private new static void F(){}}class C:B{static void F1(){F(); //invokes F of A}}
Since the new F() in B has private access, its scope does not extend to the class C. Thus the call F () in C which is valid , invokes F() of A class.
HIDING METHODS New Modifier
ABSTRACT CLASS
The abstract is modifier and used to declare a class indicates that the class cannot be instantiated.Only the derived classed can be instantiated.
ABSTRACT CLASSSyntax:abstract class base{……….……..
}class drived:base{……..…….}base b1; //errorderived d1=new derived();
ABSTRACT CLASS
Characteristics:
It cannot be instantiated directly.
It can have abstract members.
We cannot apply a sealed modifiers to it.
ABSTRACT CLASSabstract class base1{ public void fun() {
Console.WriteLine("in base class"); } }class derived1 :base1{ public void fun1() {Console.WriteLine("in derived class"); Console.ReadLine(); }}class abstracttest{ public static void Main() { derived1 d1 = new derived1();base1 b1 = new base1(); //error d1.fun1(); d1.fun(); }}.
using System;abstract class base1{ abstract public void fun(int x);} abstract class derived2 :base1{ public void fun1(int x) { Console.WriteLine("in derived class"+x); Console.ReadLine(); }} class derived1 : base1 { public override void fun(int x) { Console.WriteLine("in derived class" + x); Console.ReadLine(); } }class abstracttest{ public static void Main() { derived1 d1 = new derived1(); d1.fun(2);}}
ABSTRACT CLASS
In a derived class if you are not writing the implementation of abstract method of base class , then that derived class also be declared as an abstract class.
Need to require the definition of all (more than one)the abstract methods in derived class otherwise that can be considered as abstract class.
ABSTRACT METHODThere may be a situation where it is not possible to define a method in base class and every derived class must override that method. In this situation abstract methods are used.
When a class contains at least one abstract method, then the class must be declared as abstract class.
It is mandatory to override abstract method in the derived class.
When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.
ABSTRACT METHODWhen you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override.
When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method.
When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method.
ABSTRACT METHOD
When an instance method declaration includes the modifier abstract, the method is said to be an abstract method.An abstract method is implicitly a virtual method and does not provide any implementation. Therefore an abstract method does not have method body.
Example:public abstract void fun(intx, int y);
ABSTRACT METHODCharacteristics:It cannot have implementation;Its implementation must be provided in a non-abstract derived classes by overriding the method.
It can be declared only in abstract class.
It cannot take either static or virtual properties.
An abstract declaration is permitted to override a virtual method.
ABSTRACT Method exampleabstract class base1{ abstract public void fun();}class derived1 :base1{ public override void fun() {Console.WriteLine("in derived class"); Console.ReadLine(); }}class abstracttest{ public static void Main() { derived1 d1 = new derived1(); d1.fun();}}.
SEALED CLASSES: Preventing Inheritance
A class that cannot be subclasses is called a sealed class.In C# sealed modifier is used to prevent inheritance.Syntax:sealed class A{……..}sealed class B:someclass{………….}Sealed modifier prevents any unwanted extension to the class.A sealed class cannot be abstract .
When you want to restrict your classes from being inherited by others you can create the class as sealed class.
To create a class as sealed class, create the class using the keyword sealed.
SEALED Methods
class A{public virtual void Fun(){……….}}class B:A{public sealed override void Fun(){……….}}
Expl:The sealed method Fun() overrides the virtual method Fun() defined in class A.Any derived class of B cannot further override the method Fun().
SEALED Methods
When an instance method declaration includes the modifier sealed , the method is said to be an sealed.
A derived class cannot override this method.
A sealed method is used to override an inherited virtual method with the same signature.
It is always used in combination with override modifier.
SEALED Methods
The virtual nature of a method persists for any number of levels of inheritance.
For example there is a class “A” that contains a virtual method “M1”. Another class “B” is inherited from “A” and another class “C” is inherited from “B”. In this situation class “C” can override the method “M1” regardless of whether class “B” overrides the method “M1”.
At any level of inheritance, if you want to restrict next level of derived classes from overriding a virtual method, then create the method using the keyword sealed along with the keyword override.
SEALED Methodsclass A{public virtual void Fun(){Console.WriteLine("in A class"); Console.ReadLine();}}
class B:A{ public sealed override void Fun() { Console.WriteLine("in B class"); Console.ReadLine(); }}class sealedtest{ public static void Main() { B d1 = new B(); d1.Fun(); }}
Note:Error'B.Fun()': cannot override inherited member 'C.Fun()' because it is sealed
SEALED Methodsclass A{public virtual void Fun(){Console.WriteLine("in A class"); Console.ReadLine();}}class C: A{ public sealed override void Fun() { Console.WriteLine("in B class"); Console.ReadLine(); }}class B:C{ public override void Fun() { Console.WriteLine("in C class"); Console.ReadLine(); }}
class sealedtest{ public static void Main() { B d1 = new B();
d1.Fun(); }}
Note:Error'B.Fun()': cannot override inherited member 'C.Fun()' because it is sealed
Important characteristics of inheritance
A derived class extends its immediate base class, it can add new members to those it inherits . However it cannot change or remove the definition of an inherited members.Constructors and destructors are not inherited. All other members ,regardless of their declared accessibility in base class, are inherited. However, their accessibility in the derived class depends on their declared accessibility in the base class.
An instance of a class contains a copy of all the instance fields declared in the class and its base classes.
A derived class can hide an inherited member.
A derived class can override an inherited member.
Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism.
The example shown on next slides creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as virtual in Shape class.
using System;namespace ProgramCall{ class Shape { protected float R, L, B; public virtual float Area() { return 3.14F * R * R; }
public virtual float Circumference() { return 2 * 3.14F * R; } }
class Rectangle : Shape { public void GetLB() { Console.Write("Enter Length : ");
L = float.Parse(Console.ReadLine());
Console.Write("Enter Breadth : "); B = float.Parse(Console.ReadLine()); } public override float Area() {
return L * B; }
public override float Circumference() { return 2 * (L + B); } }
Example that shows both overriding and polymorphism
class Circle : Shape { public void GetRadius() { Console.Write("Enter Radius : ");
R = float.Parse(Console.ReadLine()); } }
class MainClass { static void Main() {
Rectangle R = new Rectangle(); R.GetLB();
Console.WriteLine("Area : {0}", R.Area());
Console.WriteLine("Circumference : {0}", R.Circumference());
Console.WriteLine();
Circle C = new Circle(); C.GetRadius(); Console.WriteLine("Area : {0}", C.Area()); Console.WriteLine("Circumference : {0}", C.Circumference());
Console.Read(); } }}
Example that shows both overriding and polymorphism continuation
Enter Length : 4Enter Breadth : 4Area : 16Circumference : 16
Enter Radius : 2Area : 12.56Circumference : 12.56
What is Polymorphism?
Compile Time Polymorphism: Method Overloading
Run Time Polymorphism: Method Overriding
Polymorphism
Example of Compile Time Polymorphism
Method Overloading- Method with same name but with different arguments is called method overloading.- Method Overloading forms compile-time polymorphism.
class A1{void hello(){ Console.WriteLine(“Hello”); }
void hello(string s){ Console.WriteLine(“Hello {0}”,s); }}
Run Time Polymorphism
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its super class.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly.
Example of Run Time Polymorphismusing System;class parent{ internal void hello(){ Console.WriteLine("Hello from Parent");Console.ReadLine();}}//End of class parentclass child : parent{ internal void hello() { Console.WriteLine("Hello from Child"); Console.ReadLine(); } static void Main(){ parent objParent = new parent();child objchild = new child();parent objpc = new child(); objpc.hello(); //parentobjchild.hello(); //childobjParent.hello(); //parent} }
Warning 1'child.hello()' hides inherited member 'parent.hello()'. Use the new keyword if hiding was intended.
Hello from Parent
Hello from Child
Hello from Parent
Example of Run Time Polymorphism (use of new)
using System;class parent{ internal void hello(){ Console.WriteLine("Hello from Parent");Console.ReadLine();}}//End of class parentclass child : parent{ internal new void hello() { Console.WriteLine("Hello from Child"); Console.Read(); } static void Main(){ parent objParent = new parent();child objchild = new child();parent obj1 = new child(); //Hello from parent obj1.hello();objchild.hello();objParent.hello();} }
Usage of newo/p will be similar to previous slide ,but without warning
o/p
Hello from Parent
Hello from Child
Hello from Parent
Example of Run Time Polymorphism (use of virtual and override)
using System;class parent{ internal virtual void hello(){ Console.WriteLine("Hello from Parent");Console.ReadLine();}}//End of class parentclass child : parent{ internal override void hello() { Console.WriteLine("Hello from Child"); Console.Read(); } static void Main(){ parent objParent = new parent();child objchild = new child();parent obj1 = new child(); //Hello from Child obj1.hello(); //childobjchild.hello(); //childobjParent.hello(); //parent} }
If we use virtual , override
o/pHello from Child
Hello from Child
Hello from Parent
Example of Run Time Polymorphism (use of virtual and override)
The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.
Casting Between Types
Typecasting between classes Or casting between the objects of base and derived classes.
C# permits upcasting of an object of a derived class to an object of its base class.We cannot downcast implicitly an object of a base class to an object of its derived classes.Example:class base1{}class derived1:base1{}….…base1 b= new derived1(); //legal upcastingderived1 d = new base1(); //error downcasting
Downcast can be achieved through an explicit cast operationderived1 d1 = (derived1)b;
Example of Run Time Polymorphism (use of type casting)
using System;class parent{ internal virtual void hello(){ Console.WriteLine("Hello from Parent");Console.ReadLine();}}//End of class parentclass child : parent{ internal override void hello() { Console.WriteLine("Hello from Child"); Console.Read(); }
static void Main() { parent objParent = new parent(); child objchild = new child(); parent obj1 = new child(); obj1.hello(); //child objchild.hello(); //child objParent.hello(); //parent
child c1 = (child)obj1; c1.hello(); //child// child c1 = (child)objParent; error
}}
o/pHello from ChildHello from ChildHello from ParentHello from Child
Interface : Multiple Inheritance
class A,B,C{……………}i.e multiple inheritance is not possible in C#.
C# provides an alternate approach known as interface, to support multiple inheritance.
Interface : Multiple Inheritance
An interface in C# is reference type. It is basically a class with some differences:
All the members of an interface are implicitly public and
abstract.
An interface cannot contain constant fields, constructors
and destructors.
It members cannot be declared static.
Since the methods in an interface are abstract, they do not
include implementation code.
An interface can inherit multiple interfaces.
Interface : Multiple Inheritance
An interface can contain one or more methods, properties, indexers, but none of them are implemented in the interface itself.
It is the responsibility of the class that implements the interface to define the code for implementation of these members.
An interface cannot extend classes .
Interface : Multiple Inheritance
Syntax:interface <interface name> {member declarations;}
Example:interface ex1{int property{get;}void display();}Interface can have modifiers public protected internal and private.We can use modifier new on nested interfaces.
Extending Interface
Interfaces can also be extended.synatxinterface name3:name1,name2 //multiple inheritance{Member of name3;}
Example:interface addition{int add(int x, int y);}interface Compute:addition{int sub(int x,int y);
}
The interface compute will have both the methods and any class implementing the interface Compute should implement both of them.
Implementing Interface
Syntax:class classname:interface name{body of class name;}
Orclass classname:superclass,interface1,interface2{body of class name;}
Example of Implementing Interfaceusing System;interface addition{ int add();} interface multiplication{ int mul();}class comp : addition, multiplication{ int x, y; public comp (int x, int y) { this.x = x; this.y = y; } public int add() { return (x + y); }
public int mul() { return (x * y); }}class interfacetest1{ public static void Main() { comp com = new comp(12, 3);addition a = new comp(2, 3); Console.WriteLine("through class ref"+a.add()); addition a2 = (addition)com; Console.WriteLine("Sum=" + a2.add()); multiplication m = (multiplication)com; Console.WriteLine("product=" + m.mul()); }} Note:
Class object is cast to interface types to reference their members.
Interface
Note:
We cannot instantiate an interface directly, i.e:addition add = new addition(); //not correct
Any number of classes can implement an interface.To implement the methods, we need to refer to the class objects as types of rather than their respective class.
Multiple Implementation of an Interface
We create an instance of each class using the new operator.Declare an object of type interface.We can cast the class type object to the interface type using as operator.Examplearea a1;
a1=c1 as area;
area is an interface, c1 is an object of class and a1 is object of an interface.
Multiple Implementation of an Interfaceusing System;interface area{ double compute(double x); }class square:area{ public double compute(double x) { return(x*x); }}class circle:area{ public double compute(double x) { return(Math.PI*x*x); }}
class interfacetest1{ public static void Main() { square sqr= new square(); circle cir = new circle(); area a1; a1.compute(3); //error
a1 = sqr as area; //casting
Console.WriteLine("Area of Square="+a1.compute(10.0));
a1 = cir as area;Console.WriteLine("Area of circle="+a1.compute(5)); Console.ReadLine(); }}
Interface and inheritanceusing System;interface display{ void print();}class base1 : display{ public void print() { Console.WriteLine("base display"); Console.ReadLine(); }}class derived1 : base1{ public new void print() { Console.WriteLine("derived display"); Console.ReadLine(); }}
class interfacetest1{ public static void Main() { derived1 d = new derived1(); d.print(); display dis = (display)d; dis.print();
//base1 b1 = new base1(); //b1.print();
}}
Note:When a base class implements an interface .An object of the derived class is converted to the interface type.Use of new modifier
interface i1{void display();}interface i2{void display();}class c1:i1,i2{public void display();}
Name collision problem: c1.display() implements i1.display() or i2.dispaly()Such problem occurs when we implement interfaces from different sources.To overcome this problem C# supports a technique known as explicit interface implementation.
Explicit Interface and implementation
Explicit Interface and implementationusing System;interface i1{ void display();}interface i2{ void display();}class c1:i1,i2{ void i1.display() //no access modifier { Console.WriteLine("i1 dispaly"); Console.ReadLine(); } void i2.display() { Console.WriteLine("i2 display"); }}
class interfacetest{public static void Main(){c1 c = new c1();i1 obj1 = (i1) c;obj1.display();i2 obj2= (i2)c; obj2.display();}}
Access modifiers are prohibited on explicit interface implementation
ABSTRACT CLASS and INTERFACE
An abstract class can use an interface in the base class list.Interface methods are implemented as abstract methods.
interface A{void Method();}abstract class B:A{…..public abstract void method();.}
Class B does not implement the interface method, It simply redeclares as a public abstract method.The class that derives from B to override and implement the method.
ABSTRACT CLASS and INTERFACE
The interfaces are similar to abstract classes. We can convert an interface into an abstract class.
interface A{void print();}similar
abstract class B{abstract public void print();}
Properties & Inheritance
The properties of a Base class can be inherited to a Derived class.
using System;class Base{public int X{get{Console.Write("Base GET");return 10;}set{Console.Write("Base SET");}}}
class Derived : Base{}class MyClient{public static void Main(){Derived d1 = new Derived();d1.X = 10;Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'}}
Static Properties
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. The set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Static Properties
using System;class MyClass{private static int x;public static int X{
get{return x;}set{x = value;}
}}
class MyClient{public static void Main(){MyClass.X = 10;int xVal = MyClass.X;Console.WriteLine(xVal);//Displays 10}}
Properties & Polymorphism
Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
Example Properties & Polymorphism
using System;class Base{public virtual int X{get{Console.Write("Base GET");return 10;}set{Console.Write("Base SET");}}}class Derived : Base{public override int X{get{Console.Write("Derived GET");return 10;}
set{Console.Write("Derived SET");}} }class MyClient{public static void Main(){Base b1 = new Derived();b1.X = 10;Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'}}
Abstract Properties
Property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. If the abstract class contains only set accessor, we can implement only set in the derived class
Abstract Properties
using System;abstract class Abstract{public abstract int X{get;set;}}class Concrete : Abstract{public override int X{get{Console.Write(" GET");return 10;}set{Console.Write(" SET");}} }
class MyClient{public static void Main(){Concrete c1 = new Concrete();c1.X = 10;Console.WriteLine(c1.X);//Displays 'SET GET 10'}}
using System;class A{ public virtual void Fun() { Console.WriteLine("in A class"); Console.ReadLine(); }}class C : A{ public void Fun() { Console.WriteLine("in B class"); Console.ReadLine(); }}class B : C{ public new void Fun() { Console.WriteLine("in C class"); Console.ReadLine(); }}This program gives warning
If you change class B : C{ public override void Fun() { Console.WriteLine("in C class"); Console.ReadLine(); }}
Error
class C : A{ public void override Fun() { Console.WriteLine("in B class"); Console.ReadLine(); }}This will work