继承关系中的菱形继承问题

继承关系中的菱形继承问题_第1张图片
伪代码:

class poweredDevice{}

class Scanner inherits from poweredDevice{
	function start(){}
}
class Printer from poweredDevice{
	function start(){}
}
class Copier inherits from Scanner.printer{}

注意:Scanner和Printer类都实现了start方法,问题来了,Copier继承的是那个start?(肯定不能同时继承,因为Java中不能多继承,只有接口能多实现)

解决方案:使用包含委托

class poweredDevice{}

class Scanner inherits from poweredDevice{
	function start(){}
}
class Printer from poweredDevice{
	function start(){}
}
Class Copier{
	Scanner scanner
	Printer printer
	function start(){
		printer.start()
	}
}

在Copier类包含一个Printer实例和一个Scanner实例。然后将start函数委托给Printer类实现。``

你可能感兴趣的:(基础,学习)