1

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?

Zac Blazic
  • 607
  • 2
  • 6
  • 17

1 Answers1

4

In other words, does it create two objects in memory?

No, it creates a single object. This single object represents a Box (and since this is a subtype of Rectangle this same object represents a Rectangle as well).

The inheritance simply ensures that the interface of the Box object is an extension of the Rectangle interface.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Okay, but what I don't understand is that I was told Box doesn't inherit the private instance variables of Rectangle, but it can access them via public methods. In that case wouldn't there have to be a Rectangle object somewhere in memory? //Confused – Zac Blazic Apr 12 '11 at 12:13
  • 2
    @Zac Blaric: You were told wrong - Box *does* inherit these, it just can't access them directly. – Erik Apr 12 '11 at 12:14
  • @Zack Blazic, well, that's a matter of wording. You could also say that it inherits them but that it can't access them. – aioobe Apr 12 '11 at 12:15
  • @Zac - related: [Does subclasses inherit private fields?](http://stackoverflow.com/questions/4716040/does-subclasses-inherit-private-fields) – user85421 Apr 12 '11 at 12:29