Can we use protected variables in other classes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can we use protected variables in other classes

Protected specifier

25th Jan 2017, 2:33 PM
Vishnu Vardhan Mamidi
Vishnu Vardhan Mamidi - avatar
2 Answers
+ 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); } }
26th Jan 2017, 2:32 AM
Matt
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.
25th Jan 2017, 3:47 PM
Faruque Hossain
Faruque Hossain  - avatar