110 likes | 161 Views
Encapsulation. Encapsulation and inheritance. Private instance variables and methods in a base class cannot be directly accessed (by name) in a derived class. They can be indirectly accessed (via accessors and mutators in the base class).
E N D
Encapsulation and inheritance • Private instance variables and methods in a base class cannot be directly accessed (by name) in a derived class. • They can be indirectly accessed (via accessors and mutators in the base class). • It’s exactly as if they don’t exist. (They can actually be defined and redefined in the derived class.)
What if private instance variables could be accessed in subclasses? Problems: • Subversion: Then to change them, all we would have to do is to make a subclass of the base class and then go ahead and change them. • Errors: The more common problem is that the accessors and mutators guard against unintentional errors.
Protected access Protected (rather than public or private) access allows: • Access by name inside its own class definition. • Access by name inside any class derived from it. • Access by name in the definition of any class in the same package (even if the class is not derived from it).
Protected access • Access between private and public • Very weak protection • Use is discouraged (use the following (viz., package access) instead)
Package access • AKA default access or friendly access. • Can be accessed by name by anything in the package but nothing outside of the package.
Package access • This is what you get when you don’t specify either public, private, or protected (hence the name default access). • (If you don’t specify a package, you belong to the default package.)
Package access • More restricted than protected. • Removes “Access by name inside any class derived from it.” if the derived class is NOT in the same package. • Packages are analogous to directories (folders). If you control the directory, you control the package.
package somePackage; public class A { public int v1; protected int v2; int v3; //package access private int v4; } package somePackage; public class B { can access v1, v2, and v3. cannot access v4. } package somePackage; public class C extends A { can access v1, v2, and v3. cannot access v4. } //default package public class D extends A { can access v1 and v2. cannot access v3 and v4. } //default package public class E { can access v1. cannot access v2, v3, and v4. } Access example
Access Access is the same for: • static variables • instance variables • static methods • ordinary methods
Summary public private protected package