java问题中的继承 [英] Inheritance in java question

查看:75
本文介绍了java问题中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是java继承中的简单问题。

假设我从一个超类创建了一个基类,比如



类丰田扩展汽车{

String modelNumber ;



公共丰田(String modelNumber)

{

this.modelNumber = modelNumber;



//其余会员数据应保留为汽车类的默认值。

}



}

Car类有自己的默认值构造函数;





所以,如果我在另一个类中实例化丰田类,那么我该如何创建一个新的丰田类,使得所有成员数据保持与父类相同,并将额外数据添加为模型号;

丰田myCar =新车()这样做吗?

有一种机制,即使我使用新的Toyota()而不是新的Car()创建一个新类,也会继承新的Toyota对象的默认值。

解决方案

丰田myCar =新车()



你做不到!

因为丰田是从Car派生的,所以它可以而且应该包含Car对象没有的信息。那些信息不能发明! :笑:



如果你能做到这一点,那就像是说苹果是一种水果,所有的水果都是苹果,这显然是胡说八道! />


您需要说的是

 Car myCar = new Toyota()

因为a汽车可以是丰田,福特,或法拉利,或者......



这给你丰田的构造函数以及汽车的构造函数。


This is just simple question in java inheritance.
Suppose I created a base class from a super class like

class Toyota extends Car{
String modelNumber;

public Toyota(String modelNumber)
{
this.modelNumber = modelNumber;

//rest of the member data should remain as the default value in the car class.
}

}
the Car class has its own constructor with the default value;


so if I am instantiating a Toyota class in another class then how do i create a new toyota class such that all the member data remain same as a parent class with extra data added as a model number;
does Toyota myCar = new Car() does that ?
is there a mechanism where even if I create a new class using new Toyota() instead of new Car() will inherit the default value for the new Toyota object.

解决方案

Toyota myCar = new Car()


You can't do that!
Because Toyota is derived from Car, it can and should contain information that a Car object doesn't. That info can't be "invented"! :laugh:

If you could do that, it would be like saying "An apple is a fruit, so all fruits are apples" which is patently nonsense!

What you need to say is

Car myCar = new Toyota()

because a Car could be a Toyota, or a Ford, or a Ferrari, or ...

And that gives you the Toyota constructor as well as the Car constructor.


这篇关于java问题中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆