简体   繁体   English

当对象被超类引用时,有没有办法访问子对象的变量?

[英]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 ? 有没有其他方法来访问子类变量,父类指向子类对象?

scenario 脚本

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.

相关问题 什么是子对象与其父对象的关联? - What is a child object's association to its parent referred to as? 使用super()或对象访问父类中的变量? - Access variable in parent class using super(), or an object? 子类可以称为其超类的类型吗? - Can a subclass be referred to as the type of its super class? Java继承:为什么引用超类变量 - Java Inheritance: Why super class variable is referred “ JAXBException:类org.example.entity.Foo或其任何超类对此上下文都是已知的。”当对象位于外部.jar中时 - “JAXBException: class org.example.entity.Foo nor any of its super class is known to this context.” when object is in external .jar JAVA - 类和它的对象,超级 - JAVA - class and it's object, super 子类对象的超类引用变量访问子类的属性而不是父类的属性 - Super-class reference variable to a sub-class object accesses the subclass's attribute instead of the super's 对象的超类可访问性 - an Object's super class accessibilty 当spy()真实对象时,超类字段未分配任何值 - super class field is not assigned to any value when spy() the real object 类加载器引用的类对象? - class object referred by class loader?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM