+ 2
[SOLVED] Java Protected Access
Why the output of this code is 0? Protected variables cannot be accessed from Main Class. Can somebody explain? https://code.sololearn.com/c2YhHgK0SG38/?ref=app
12 ответов
+ 4
In java, we can access Protected modifier in same package as well as sub class package.
+ 2
If you want to prevent an access from inside the package, then chose the "private" modifier.
See here a nice table:
https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in
+ 2
The output is 0 because you have not initialized any values to x and y. The default value of x and y is 0.
So t.x+t.y= 0+0= 0
Initialize values to x and y and try it.
protected members can be accessed from within the same class+ different class of same package+ subclass of same package+ subclass of different package
+ 1
Orango Mango protected modifier is accessible in the same package[consider the code you wrote is in the same file] https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
+ 1
Protected is not default.
Protected gives access for subclasses in same and other package.
Default = no modifier: gives only access for subclass in same package.
+ 1
KODER999 , yes, that's what I wrote. But from all packages.
And if you don't use any modifier (default) only from subclasses in same package.
So "no modifier" or default is a "stronger" protection as using "protected".
+ 1
KODER999 public is from all packages, but not only from subclasses of the class.
Maybe you will have a look at my answer above here. There is a table on stackoverflow.com that shows the behavior.
0
I guess that's because they placed in one package. Google it, maybe you'll get it better