C++中的多重继承及JAVAC#中的单继承——钻石之死

http://www.knowledgesutra.com/discuss/tftpc-difference-questions.html


The syntax of C# is very close to Java, more so than it is to C++. Like Java it has interfaces and a single-inheritance hierarchy

What does that mean? Let's start with the whole single-inheritance hierarchy thing. C++ allows for multiple inheritance, that means a class can have more than one super class. There are inherant problems with multiple inheritance, however. Let me give you the classic Diamond Of Death scenario. You're given four classes. Classes B and C are subclasses of Class A, and Class D --using multiple inheritance-- is a subclass of both B and C. Class A sits at the top of the heirarchy, B and C sit on a level below and D is on the 3rd and last level(if you play connect the dots following the classes in the following order A-B-D-C-A you get a diamond).
Let say both classes B and C override the method 'foo()' of their super class A, but class D inherits from B and C without overriding any methods. How does D resolve calls to its inherited method 'foo()'. It can't. Hence the fabled'Diamond of Death' (queue menacing sound). 
The Java designers decided to implement a single-inheritance scheme to remedy this issue. That meant that a class can inherit-from/extend/subclass one and only one super class. To compensate for the loss of functionality that multiple inheritance provided, Java introduced interfaces. Think of them as classes whose methods have no body, that is, they have no implementation. 

Interfaces look something like this:
CODE
interface Movable{
public void up();
public void down();
public void left();
public void right();
}



Now, in addition to their  extends keyword Java and C# also have the  implements keyword for interfaces. When the implements keyword is followed by the name of an interface, a class is required to implement all the interface's methods as seen below:
CODE
class Car extends Vehicle implements Movable{
// ...other code


public void up() {
// implementation goes here
}

public void down() {
// implementation goes here
}

public void left() {
// implementation goes here
}

public void right() {
// implementation goes here
}
}


A class can implement as many interfaces as it likes and since every class that implements an interface has to provide its own implementation of that interface's methods the DOD (Diamond of Death) scenario never arises.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值