Reputation: 33
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?
Upvotes: 3
Views: 1464
Reputation: 1331
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.Upvotes: 1
Reputation: 2282
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
Upvotes: 0
Reputation: 16208
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);
}
Upvotes: 0
Reputation: 5140
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()
Upvotes: 1
Reputation: 727027
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);
Upvotes: 1
Reputation: 12890
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!
Upvotes: 7
Reputation: 3077
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.
Upvotes: 1