java中如何返回父类
我对java相当陌生,在我的代码中我需要一个子类来创建其父类的对象,我很确定有一个java关键字可以做到这一点,但是当我在Google上搜索它时什么也没有出现。
I am fairly new to java and in my code I need a child class to be able to make a an object of its parent class I am pretty sure there is a java keyword that does this but when I searched Google for it nothing came up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
多态性的一个很好的特性是子类型的每个实例也是父类型的实例。所有这些“返回父类型的对象”;
A nice feature about polymorphism is that every instance of the child type is also an instance of the parent type. All of these "return an object of the parent type";
使用 super(); 怎么样?
how about using super();
您可能会想到“super”作为关键字,但这并不符合您的描述。
父类在 Java 中并不特殊:
You may be thinking of "super" for the keyword, but that doesn't do what you describe.
A parent class isn't special in Java:
我不知道你为什么需要这样做。您只需返回子级的一个新实例并将其转换为父级即可。这应该有效。如果您有重写的方法或类似的方法,并且希望能够访问父方法,那就是另一个问题了。否则,您可以直接向上转换:
要向上转换 Child 对象,您所需要做的就是将该对象分配给 Parent 类型的引用变量。父引用变量无法访问仅在子级中可用的成员。
因为 Parent 引用了 Child 类型的对象,所以您可以将其强制转换回 Child。之所以称为向下转型,是因为您将对象强制转换为继承层次结构中的类。向下转型要求您将子类型写在括号中。例如:
如果您需要能够获取父级的实例,那么正如有人建议的那样,只需让您的孩子
返回 new Parent()
即可。I don't know why you would need to do this. You can just return a new instance of the child and cast it to the parent. This should work. If you have overridden methods or something of that sort and want to be able to access parent methods that is a different issue. Otherwise you can just upcast:
To upcast a Child object, all you need to do is assign the object to a reference variable of type Parent. The parent reference variable cannot access the members that are only available in Child.
Because parent references an object of type Child, you can cast it back to Child. It is called downcasting because you are casting an object to a class down the inheritance hierarchy. Downcasting requires that you write the child type in brackets. For example:
If you need to be able to get instances of the parent then as someone has recommended, just have your child
return new Parent()
.