Private access modifier and Inheritance (Inheritance implementation in Java)

M

maxw_cc

Hi everybody!

I have a question about how Inheritance is implemented in Java.
This code example is in the JLS
(Java Language Specification) "8.2.1.3 Inheritance with private"
Section:

class Point {
int x, y;
void move(int dx, int dy) {
x += dx; y += dy; totalMoves++;
}
private static int totalMoves;
void printMoves() { System.out.println(totalMoves); }
}

class Point3d extends Point {
int z;
void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz; totalMoves++;
}
}


A guy on the web gave the following explanation
for the previous code snippet:

<quote>
--------------------------------------------------------------------------------
You need to look at what happens on class load.
When Point3d is created with the new function, An instance of each
Object (in order) are created.
Object
Point
Point3D

Point3D now can access those Attribute and Methods in Point and Object
just as if they where it's own EXCEPT private methods and variables
(And package variables and methods in Object since Object is in a
different package than Point or Point3D). So, while there is a copy of
totalMoves in the memory space for Point, Point3D can not access it
directly so, for sake of clearity, it said to "Not be Inherited". Now,
x and y still exist in the memory space for Point but, since ther is
no access modifier, the default access level is Package and Point and
Point3D are in the Same package so, Point3D can access these directly
so, they are "Inherited"
--------------------------------------------------------------------------------
</quote>

Is this the way how it always happens?
I mean whenever you create an object of a class in the heap, are
always implicitly created objects for each of its superclasses?
Is this the way of how Java implements inheritance internally?

Thank you very much to everybody in advance...

Max
 
M

Martijn van Steenbergen

class Point {
int x, y;
void move(int dx, int dy) {
x += dx; y += dy; totalMoves++;
}
private static int totalMoves;
void printMoves() { System.out.println(totalMoves); }
}

class Point3d extends Point {
int z;
void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz; totalMoves++;
}
}

This will not work properly. Whenever move(int dx, int dy, int dz) in
Point3d is called, it first calls super.move(int dx, int dy) which
increments totalMoves, then totalMoves is incremented again. Plus,
Point3d cannot increment totalMoves, because it does not have access to
the variable, since it's declared private in Point.

Have a good day,

Martijn.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top