创建子类对象是否也会创建其超类对象?
这是我的意思的一个例子:
public class Rectangle
{
private int length;
private int breadth;
.
.
}
public class Box extends Rectangle
{
private int height;
.
.
}
当您:
Box b = new Box();
它是否创建一个 Box 以及一个 Rectangle 对象,其中矩形不能直接访问,而只能通过 Box 对象访问。换句话说,它是否在内存中创建了两个对象?
Heres an example of what I mean:
public class Rectangle
{
private int length;
private int breadth;
.
.
}
public class Box extends Rectangle
{
private int height;
.
.
}
When you:
Box b = new Box();
Does it create a Box as well as a Rectangle object, with the rectangle not directly accessible, but only accessible through the Box object. In other words, does it create two objects in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它会创建一个对象。这个单个对象代表一个
Box
(并且由于这是Rectangle
的子类型,因此同一对象也代表一个Rectangle
)。继承只是确保
Box
对象的接口是Rectangle
接口的扩展。No, it creates a single object. This single object represents a
Box
(and since this is a subtype ofRectangle
this same object represents aRectangle
as well).The inheritance simply ensures that the interface of the
Box
object is an extension of theRectangle
interface.