You need to make it ((A)b).x
to properly type cast it
Note : You are trying to type cast the property x
to type A
. That's the error!
Question
Let say I have the following java classes:
Class A:
public class A {
private int x;
public A(int x){
this.x = x;
}
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println((A)b.x);
}
}
Class B:
public class B extends A {
public int y;
public B(int x, int y){
super(x);
this.y = y;
}
}
Why does the compiler marks the access to x on this line
System.out.println((A)b.x);
as an error, even though I'm trying to access x from the class in which it is defined?
Is it because of:
1. the use of polymorphism?
2. the use of a static method?
3. the use of the main method?
Solution
You need to make it ((A)b).x
to properly type cast it
Note : You are trying to type cast the property x
to type A
. That's the error!
OTHER TIPS
int x
is private
therefore it can't be reached from outside of the scope of the class. You could mark it as protected
. This way it will still have limited scope. Classes that extend A will be able to access the variable freely.
This is because the dot operator has precedence over the cast operator. This will work, because it forces the cast operator to be applied before the dot operator:
System.out.println(((A)b).x);
When you write (A)b.x
, the compiler try to cast b.x
into A
, but x
is an int
Moreover, you don't need to cast b
into A
and you can't access b.x
because x
is a private field.
You may need a getter for this, like b.getX()
You have follwing issues
"Field not visible"
Error,Because you trying to access private method of parent class.
operator has precedence over cast operatorprivate
,which is not inherited. Even if you cast to parent you cant access private members using child object.Because you are trying to cast an int
into A
. You need to wrap the cast around the object and then call .x
.
Your call is equivalent to (A)(b.x)
, when it should be ((A)b).x
.
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println(((A)b).x);
}
Basically, two issues exist here.
One being that int x
is private
so it cannot be accessed from the sub-class.
Now even if you change the access criteria of int x
to public
or protected
; the code will still not work because (A)b.x
will try to typecast an integer (read x
) to an object (read A
). Instead of this, you should use ((A)b).x