Members Access Modifiers
Because method and variable members are usually given access control in exactly the same way, we'll cover both together.
Whereas a class can use just two of the four access control levels (default or public ), members can use all four:
- public
- protected
- default
- private
Public Members
When a method or variable member is declared public, it means all other classes, regardless of the package they belong to, can access the member (assuming the class itself is visible).
example:
public void methodA() { }
public int year;
Private Members
Members marked private can't be accessed by code in any class other than the class in which the private member was declared.
A method marked private cannot be overridden.
example:
private void methodB() {}
private String name;
Protected and Default Members
The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
Note: Default members can be accessed only from the same package and cannot be through inheritance.
example:
abstract class Car {
double price // Default member;
protected void goFast(); // Protected method
void getModel(){}; // Default method
Because method and variable members are usually given access control in exactly the same way, we'll cover both together.
Whereas a class can use just two of the four access control levels (default or public ), members can use all four:
- public
- protected
- default
- private
Public Members
public int year;
A method marked private cannot be overridden.
private String name;
The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
Note: Default members can be accessed only from the same package and cannot be through inheritance.

No comments:
Post a Comment