[SOLVED] Java Protected Access | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 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

25th Apr 2021, 9:10 AM
Orango Mango
Orango Mango - avatar
8 Respuestas
+ 4
In java, we can access Protected modifier in same package as well as sub class package.
25th Apr 2021, 10:51 AM
Java Developer
Java Developer - avatar
+ 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
25th Apr 2021, 9:58 AM
Coding Cat
Coding Cat - avatar
+ 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
26th Apr 2021, 5:18 AM
Chinmaya Moorthy S
Chinmaya Moorthy S - avatar
+ 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
25th Apr 2021, 9:50 AM
Ananiya Jemberu
Ananiya Jemberu - avatar
+ 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.
25th Apr 2021, 3:22 PM
Coding Cat
Coding Cat - avatar
+ 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".
25th Apr 2021, 3:47 PM
Coding Cat
Coding Cat - avatar
+ 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.
25th Apr 2021, 4:06 PM
Coding Cat
Coding Cat - avatar
I guess that's because they placed in one package. Google it, maybe you'll get it better
25th Apr 2021, 9:21 AM
Nazeekk - avatar