When declaring a variable in Java,what's the difference between "protected" and having "no access modifier"? Is it the same?
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. Protected: The access level of a protected modifier is within the package and outside the package through child class.
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
Default: When no access modifier is specified for a class, method, or data member – It is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.
The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors. We divide modifiers into two groups: Access Modifiers - controls the access level. Non-Access Modifiers - do not control access level, but provides other functionality.
Both protected and no access modifier variables are accessible in the same package, but protected variables can be accessed by a subclass instance anywhere (in any package).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With