8.7.11 Inheritance

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

Classes support single inheritance, and the type object is the ultimate base

class for all classes.

The classes shown in earlier examples all implicitly derive from object.

The example

using System;

class A

{

public void F() { Console.WriteLine("A.F"); }

}

shows a class A that implicitly derives from object. The example

class B: A

{

public void G() { Console.WriteLine("B.G"); }

}

class Test

{

static void Main() {

B b = new B();

b.F(); // Inherited from A

b.G(); // Introduced in B

Chapter 8 Language Overview

41

A a = b; // Treat a B as an A

a.F();

}

}

shows a class B that derives from A. The class B inherits A.s F method, and

introduces a G method of its own.

Methods, properties, and indexers can be virtual, which means that their

implementation can be overridden

in derived classes. The example

using System;

class A

{

public virtual void F() { Console.WriteLine("A.F"); }

}

class B: A

{

public override void F() {

base.F();

Console.WriteLine("B.F");

}

}

class Test

{

static void Main() {

B b = new B();

b.F();

A a = b;

a.F();

}

}

shows a class A with a virtual method F, and a class B that overrides F.

The overriding method in B contains

a call, base.F(), which calls the overridden method in A.

A class can indicate that it is incomplete, and is intended only as a base

class for other classes, by including

the modifier abstract. Such a class is called an abstract class. An

abstract class can specify abstract

members.members that a non-abstract derived class must implement. The

example

using System;

abstract class A

{

public abstract void F();

}

class B: A

{

public override void F() { Console.WriteLine("B.F"); }

}

class Test

{

static void Main() {

B b = new B();

b.F();

A a = b;

a.F();

}

}

introduces an abstract method F in the abstract class A. The non-abstract

class B provides an implementation

for this method.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航