[英]Is there any way to access child object's variable when the object is referred by its super class?
Is there any other way to access child object's variable when the object is referred by its parent class other than casting the object to child class? 除了将对象强制转换为子类,除了父类引用对象时,还有其他方法可以访问子对象的变量吗?
class parent{
int parentData;
}
class child extends parent{
int childData;
}
parent obj =new child();
obj.childData =10 ; //is getting error
((child )obj).childData=10; // is working fine
is there any other way to access child class variable where child class object is pointed by parent class ? 有没有其他方法来访问子类变量,父类指向子类对象?
If my parent class has 2-3 child class that are differ with parent class by only one variable and i tried to refer all child class object with parent class.In some point i need to get child variable what should i do ? 如果我的父类有2-3个子类,只有一个变量与父类不同,我试图用父类引用所有子类对象。在某些时候我需要得到子变量我该怎么办? do i need to redesign ?
我需要重新设计吗?
The parent class should contain only behavior that is common to all child classes. 父类应仅包含所有子类共有的行为。
If what you are trying to implement in the parent class is indeed common behavior you might want to look in to the Template method pattern . 如果您尝试在父类中实现的内容确实是常见行为,则可能需要查看模板方法模式 。
If what you are implementing is different behavior over the child classes, do not try to shoehorn it into the parent class but implement it in the child classes. 如果您正在实现的是与子类不同的行为,请不要试图将其变为父类,而是在子类中实现它。 If these implementations share common parts, you could extract this to a common method either in the parent or a helper class.
如果这些实现共享公共部分,则可以将其提取到父级或辅助类中的公共方法。
How come parents started to know thier childs in java? 为什么父母开始在java中认识他们的孩子? That's not possible.
那是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.