III. Access and hidden base class (1) Access base class member
Access to the base class via the Base key:
Methods of rewritten by other methods on the base class.
Specifies the base class constructor that should be called when the party instance is created.
Base class access can only be performed in a constructor, an instance method, or an instance attribute accessor.
It is wrong to use the base key from the static method.
Example: Both Person and derived class Employee in the following program have a method called getInfo. By using the base keyword, you can call the GetInfo method on the base class from the derived class.
Using system; public class person {protected string ssn = "111-222-333-444"; protected string name = "Zhang San"; public virtual void getinfo () {console.writeline ("Name: {0}", Name ); Console.writeline ("Number: {0}", SSN);}} Class Employee: Person {public string id = "abc567efg23267"; public override void getInfo () {// Call the base class GetInfo method: base. GetInfo (); Console.Writeline ("Member ID: {0}", ID);}} Class TestClass {public static void main () {EMPLOYEE E = New Employee (); E.GetInfo ();}}
Output: Name: Zhang San Number: 111-222-333-444 Member ID: ABC567EFG23267 Example: Derived class with base class for communication.
using System; public class Parent {string parentString; public Parent () {Console.WriteLine ( "Parent Constructor.");} public Parent (string myString) {parentString = myString; Console.WriteLine (parentString);} public void print ( ) {Console.writeline ("I'm a Parent Class.");}} Public class child: parent {public class (): base ("from derived") {console.writeline ("Child Constructor.");} Public void print () {base.print (); console.writeline ("I'm a child class.");} public static void main () {child child = new child (); child.print (); (PARENT) CHILD .print ();}}