基础,派生和继承类问题.. [英] Base, derived and inheritance classes questions..

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

问题描述

如果我有:

If i have :

class Car{
// any fields here.
}
 
class BMW : Car{
// any fields here.
}
 
void main(){
BMW myBMW = new BMW(); // Case 1 -> it works
Car myBMW = new BMW(); // Case 2 -> it works
}





我的问题是案例1 =案例2?什么是差异和优点。哪一个更好?



my question is Case 1 = Case 2 ? and what's difference and advantages. and which one is better ?

推荐答案

您可以使用它的ancerstor(父级或上级)类型的引用来访问任何对象。当然,在这种情况下,您只能访问该级别定义的字段。这就是区别。



BMW myBMW =新BMW();

您可以访问所有字段在对象汽车宝马中定义。



Car myCar = new BMW();

您只能访问<中定义的字段code>对象和 Car 。仍然myCar是对BMW型物体的改造。因此将其投回宝马是有效的。
You can access any object using a reference of it's ancerstor's (parent or above) type. Of course in this case you have access only to the fields defined at that level. That's the difference.

BMW myBMW = new BMW();
You can access all field defined in Object, Car and BMW.

Car myCar = new BMW();
You can access only field defined in Object and Car. Still myCar is a renference to a BMW type object. Thus casting it back to BMW is valid.


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

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