C # Inheritance mechanism accesses and hides base class members

Source: Internet
Author: User

(1) Access to base class members

Access the members of the base class through the base keyword:

Calls a method on the base class that has been overridden by another method.
Specifies the base class constructor that should be called when creating an instance of a derived class.
Base class access can only be done in constructors, instance methods, or instance property accessors.
Using the base keyword from a static method is an error.

Example: the base class person and derived class Employee in the following program have a method named Getinfo. The Getinfo method on the base class can be called from a derived class by using the base keyword.

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 GetInfo method of the base class:
Base. GetInfo ();
Console.WriteLine ("Member ID: {0}", id);
}
}
Class TestClass {
public static void Main () {
Employee E = new Employee ();
E.getinfo ();
}
}

Program Run output:

Name: Zhang San
Item No: 111-222-333-444
Member id:abc567efg23267

Example: Derive a similar 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 Child (): 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 ();
}
}

Program Run output:

From Derived
Child Constructor.
I ' m a Parent Class.
I ' m a child Class.
I ' m a Parent Class.

Description

1. Derived classes can communicate with the base class during initialization.

The above code demonstrates how to implement the same base class communication in the subclass's constructor definition. The semicolon ":" and the keyword base are used to invoke the constructor of the base class with the corresponding parameters. In the output, the first line indicates that the constructor of the base class is called first, in fact the argument is the string "from Derived".

2. Sometimes, for a method that has a defined base class, it is intended to redefine its own implementation.

The child class can redefine the implementation of the print () method on its own. The print () method of child overrides the Print method in the parent. The result is that the Print method in the parent class is not called unless specifically specified.

3. In the print () method of the child class, we specifically indicate that the print () method in the parent class is called.

The method name is preceded by "base", and once the "base" keyword is used, you can access the base class's members with public or protected permissions. The execution results of the print () method in the child class appear in the third and fourth rows above.

4. Another way to access a base class member is through an explicit type conversion.

This is done in the last statement in the main () method of the child class. Remember: A derived class is a special case of its base class. This fact tells us that you can convert a data type in a derived class so that it becomes an instance of the base class. The last line of the above code actually executes the print () method in the parent class.

(2) Hide base class members

Think about it, if all the classes can be inherited, what are the consequences of the misuse of the inheritance? Class hierarchy will become very large, the relationship between the big class is disorganized, the understanding and use of the class will become very difficult. Sometimes, we don't want classes that we write to be inherited. At other times, some classes are no longer necessary to be inherited. C # presents the concept of a sealed class (sealed class) to help developers solve this problem.

The sealed class uses the sealed modifier in the declaration, which prevents the class from being inherited by other classes. If you attempt to use a sealed class as the base class for other classes, C # will prompt an error. Of course, sealed classes cannot be abstract classes at the same time, because abstractions always want to be inherited.

On what occasions are sealed classes used? Sealed classes can prevent other programmers from inadvertently inheriting the class. And the sealing class can be optimized for the run-time effect. In fact, there can be no derived class in a sealed class. If a virtual member function exists in a sealed class instance, the member function can be converted to non-virtual, and the function modifier virtual no longer takes effect.

Let's look at the following example:

Bstract class A
{
public abstract void F ();
}
Sealed class B:a
{
public override void F ()
Specific implementation code for {//F}
}

If we try to write the following code

Class c:b{}

C # will point out this error and tell you that B is a sealed class and cannot attempt to derive any class from B.

(3) Sealing method

We already know that the use of sealed classes can prevent inheritance of classes. C # also presents the concept of a sealing method (Sealedmethod) to prevent overloading of the method in a derived class of the class where the method resides. You can use the sealed modifier for a method, which we call the method a sealing method.

Each member method that is not a class can be used as a sealing method, and the virtual method of the base class must be overloaded to provide a concrete implementation method. Therefore, in the declaration of a method, the sealed modifier is always used in conjunction with the override modifier. Take a look at the following example code:

Using System;
Class A
{
public virtual void F ()
{Console.WriteLine ("A.F");}
public virtual void G ()
{Console.WriteLine ("A.G");}
}
Class B:a
{
Sealed override public void F ()
{Console.WriteLine ("B.f");}
Override public void G ()
{Console.WriteLine ("B.G");}
}
Class C:b
{
Override public void G ()
{Console.WriteLine ("C.G");}
}

Class B overloads the two virtual methods in base Class A, where the F method uses the sealed modifier to become a sealed method. The G method is not a sealed method, so in the derived class C of B, method G can be overloaded, but method F cannot be overloaded.

(4) Hiding base class members with the new modifier

Use the new modifier to explicitly hide members inherited from a base class. To hide an inherited member, declare the member in the derived class with the same name and decorate it with the new modifier.

Consider the following class:

public class MyBase
{
public int x;
public void Myvoke ();
}

Declaring a member with a myvoke name in a derived class hides the Myvoke method in the base class, which is:

public class Myderived:mybase
{New public void Myvoke ();}

However, because field X is not hidden by a similar name, it does not affect the field.

Hiding names by inheritance takes one of the following forms:

A, the introduction of constants, designations, attributes, or types in a class or struct hides all base class members with the same name.

B, introduce methods in classes or structs to hide properties, fields, and types that have the same name in the base class. It also hides all base class methods with the same signature.

C, introducing indexers in a class or struct hides all base class indexers with the same name.

Note: It is an error to use both new and override on the same member. Using new and virtual at the same time guarantees a special point. Using the new modifier in a declaration that does not hide an inherited member will issue a warning.

Example 1: In this example, the base class MyBaseC and the derived class Myderivedc use the same field name X, which hides the value of the inherited field. This example illustrates the use of the new modifier. It also shows how to access the hidden members of the base class using the fully qualified name.


Using System;
public class MyBase
{
public static int x = 55;
public static int y = 22;
}
public class Myderived:mybase
{
new public static int x = 100; Use new to hide the X of the base class
public static void Main ()
{
Print x:
Console.WriteLine (x);
To access the X of the hidden base class:
Console.WriteLine (mybase.x);
Print y not hidden:
Console.WriteLine (y);
}
}

Output: 100 55 22

If you remove the new modifier, the program will continue to compile and run, but you will receive the following warning:

The keyword new is required on ' myderivedc.x ' because it hides inherited member ' mybasec.x '.

If the nested type is hiding another type, as shown in the following example, you can also modify this nested type with the new modifier.

C # Inheritance mechanism accesses and hides base class members

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.