I'm trying to understand what these modifiers really means, beacause I think there's a lot of confusion about what they do or don't do. So, here's what I know:
four access modifiers are used:
public
, protected
, private
, no modifier(package private)
.
1) with respect to members inside its definition: a class can access every one of them no matter what the access modifier.
2) with respect to another class, which it doesn't inherit from nor shares the same package: it can access only members which are marked as public
.
3) with respect to another class in the same package,but which it doesn't inherit from: it can access only members marked as public
, protected
and have no modifier(package private)
.
now comes the tricky part (at least for me..)
4) if a class A inherits from another class B, but doesn't share the same package, A has all the members (fields and methods) declared public
and protected
in B.
BUT with respect to AN INSTANCE of B, A can only access public
members (not protected
or no modifier(package private)
ones, am I right on this??).
5) if a class A inherits from another class B, and they share the same package, A has all the members (fields and methods) declared public
, protected
AND no modifiers(package private)
in B (am I right??).
Since A and B are in the same package, A is able to access protected
, no modifier(package private)
members of any instance of B (and of course public
ones as well).
In addition, since A is-a B which members will another class (say, C) trying to access a member of A (of one of its instance of course, but let's keep it simple) be able to get to??
I know for sure C will be able to access public
members, but what about protected
, or no modifier(package private)
ones in case 4 and 5?
(I leave private
aside, since those members can only be accessed inside the defining class)
please, help!
This is what happens in terms of access/inheritance :
package one;
//class with all kind of modifiers
public class A {
protected void methodProtected(){}
public void methodPublic(){}
void methodDefault(){}
private void methodPrivate(){}
}
//same package,no inheritance
package one;
public class B {
{
new A().methodDefault();
new A().methodProtected();
new A().methodPublic();
}
}
//same package,inheritance
package one;
public class C extends A {
{
new A().methodDefault();
new A().methodProtected();
new A().methodPublic();
methodDefault();
methodProtected();
methodPublic();
}
}
//different package,inheritance
package two;
import one.A;
public class D extends A{
{
new A().methodPublic();
A a = new A();
//compiler error: can't access protected members
//a.methodProtected();
methodPublic();
methodProtected();
}
}
//different package,no inheritance
package two;
import one.*;
public class E {
{
new A().methodPublic();
}
}
now, I would like to know what happens when E tries to access B,C or D, and what if E inherits from A or one of the other classes, or is in the same package?? what a mess...