0
Can we use protected variables in other classes
Protected specifier
2 Respuestas
+ 1
As the other commenter said, the "protected" access modifier allows access to classes in the same package. IT ALSO, allows subclasses of that class to access the methods/variables. Default (aka package protected) access allows access only to classes in the same package. Default access modifier is implicit when no access modifier is declared in classes and abstract classes. Remember interface methods are implicitly public, static, and final.
Remember you can always try and write some code to see if it breaks. The following code will show that protected access allows inheritance to subclasses.
package one;
public class A{
protected static String message = "Hello, world!"
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a new file:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
package two;
Import one.A;
public class B extends A{
public static void main(String args[]){
System.out.println(A.message);
}
}
0
The protected keyword makes things visible within the same package. Which is the case, because both of your classes are in package mypackage.
If your other class in same package you can access that.