as I understood, In java all the variables are refernces.
On the next code:
class Parent {
public int x = 12;
}
class Child extend Parent {
public int x = 42;
}
Parent p = new Parent();
System.out.println(p.x);
12
Child c = new Child();
System.out.println(c.x);
42
p = c; // be careful here!
System.out.println(p.x);
12
I think that there is no Slicing here, because we talk about refernces. For that reason, I don't understand why "12"
is printed. p
is now points to the area of c
, and c.x
is 42.
The same is happening in the next code on C++:
class Parent {
public:
void ex开发者_运维百科ample () { cout << "Parent" << endl; }
};
class Child : public Parent {
public:
void example () { cout << "Child" << endl; }
};
Parent * p = new Parent();
p->example()
Parent
Child * c = new Child();
c->example()
Child
p = c; // be careful here!
p->example()
Parent
You are hiding members, not overriding. For the Java example, you cannot override a field. You need to use a function. For the C++ example, your function in Parent
must be virtual to be overridden by Child
. Otherwise you simply hide the function.
C++:
class Parent {
public:
virtual void example () { cout << "Parent" << endl; }
};
class Child : public Parent {
public:
void example () { cout << "Child" << endl; }
};
In Java, you cannot override a field, you can only hide it. Child has two fields Parent.x
and Child.x
. The reference type determines which field you means by .x
for the java side you are declaring 2 separate variables
meaning that for a Child c
there's c.x
and a ((Parent)c).x
that are different variables with their own values
That's because you user p.x, not c.x. The field x is not overriden by Child (as, for example, a method getX() would be). Instead, it is in the subobject, corresponding to a Child class. So, you actually have 2 x: Parent.x and Child.x.
In Java you can only hide the field and not override it.
For Java
p=c
Now p has the reference of c thus you get answer =12
精彩评论