Inheritance allows us to define another class based on one class, which makes it easier to create and maintain applications. It also facilitates the reuse of code and saves development time.
Using System;Namespace Inheritanceapplication{ Class Shape { Public voidSetWidth(IntW) {Width=W; } Public voidSetHeight(IntH) {Height=H; } Protected IntWidth; Protected IntHeight; } Derived classes Class Rectangle: Shape { Public IntGetarea() { Return (Width*Height); } } Class Rectangletester { Static void Main(String[]Args) { Rectangle Rect = New Rectangle(); Rect.SetWidth5rect.7//the area of the printed object console. Writeline ( "total area: {0}" , Rect. Getarea console. Readkey} }} /span>
When the above code is compiled and executed, it produces the following results:
Total area:
Initialization of the base class
Derived classes inherit the member variables and member methods of the base class. Therefore, the parent class object should be created before the child class object is created. You can initialize the parent class in the member initialization list.
The following program demonstrates this:
Using System;Namespace Rectangleapplication{ Class Rectangle { Member variables Protected DoubleLength; Protected DoubleWidth; Public Rectangle(DoubleL, DoubleW) {Length=L;Width=W; } Public Double Getarea() { ReturnLength*Width; } Public void Display() { Console.WriteLine("Length: {0}",Length); Console.WriteLine("width: {0}",Width); Console.WriteLine("Area: {0}", Getarea()); } }End Class Rectangle Class Tabletop : Rectangle { Private DoubleCost; Public Tabletop(DoubleL, DoubleW) : Base(L,W) { } Public Double Getcost() { DoubleCost;Cost= getarea () * 70; return Cost;} public void display () {base. Displayconsole.writeline ("cost: {0}", Getcost ());} } class Executerectangle {static void Main (string[] args) {Tabletop T = new Tabletop (4.5, 7.5); T.display (); Console.ReadLine (); }}}
C # does not support multiple inheritance . However, you can use interfaces to implement multiple inheritance. The following program demonstrates this:
Using System;Namespace Inheritanceapplication{ Class Shape { Public voidSetWidth(IntW) {Width=W; } Public voidSetHeight(IntH) {Height=H; } Protected IntWidth; Protected IntHeight; } Base class Paintcost Public Interface Paintcost { IntGetcost(IntArea); } Derived classes Class Rectangle : Shape, Paintcost { Public IntGetarea() { Return (Width*Height); } Public IntGetcost(IntArea) { ReturnArea* 70; } } Class Rectangletester { Static void Main(String[]Args) { Rectangle Rect = New Rectangle(); int Area;rect.5rect.7 area =< Span class= "PLN" > rect.//the area of the printed object console. WriteLine ("total area: {0}", Rect.getarea ()); Console.WriteLine ("Total Paint cost: ${0}", Rect.getcost (area)); Console.readkey (); } }}
Basic knowledge of C # review (vi)---inheritance