Hello, I am studying for SCJP. I got this coding from a study guide.Could you please explain this compile time error. Thank You Very Much. package point; class Point { protected int x =10; } package threepoint; import poin.Point; class ThreePoint extends Point { int x =10; void aMethod(Poin p) { p.x += this.x; } }
SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
You did not say what the compile error was... but from what I see, I think it has to do with type Point in the method header, you should declare Point as public otherwise u cannot access it in another package
"Did anyone understand what I have just explained? ... because I did not!"
So sorry about it. It says it is not possible to access the super class variable becuase the Point p object is not part of the implementation of the ThreePoint class. Think all the classes are public. The problem is in the method. Hope I the problem is clearly presented. Thank you.
SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Assuming that the class Point is indeed public. The error is simply because you are trying to access a protected variable 'x' in object 'p' of Class 'Point' outside the package. I guess this is not permitted. But u could access the variable as 'super.x' inside ThreePoint. Quoted from somewhere outside: Protected access hides the class's methods and attributes from classes that exist outside of the class's package. This means that classes within the same package can access protected methods and attributes. When subclassing, the class' subclasses can also access the protected methods and attributes.
Hi Ransika There is a limitation when you try to access any protected member outside the package in which it is defined, then you can call the proctected member only by using subclass reference not by the super class reference so in this case you are using Point p refernce to call protected member which is not possible so that's why it is giving you the compile time error. Regards Rashi