Reputation: 1881
According to the second table of documentation (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) a member with no identifier is not visible to a subclass.
But, when I run the following sample code, "1" (content of b) is printed!
class Class1{
private int a=0;
int b=1;
protected int c=2;
public int d=3;
}
class Class2 extends Class1{ }
public class HelloWorld{
public static void main(String []args){
Class2 klass=new Class2();
System.out.println(klass.b);
}
}
If a member, with no access modifier, is not accessible from a subclass why is it printed in this example?
It should throw an error, like in private access modifier, shouldn't it?
Upvotes: 1
Views: 2566
Reputation: 1
In Same package, Child class can access all the member element of its parent class and thats why it is able to print the SOP statement.Because default modifier is know as package private means it can be accessed in same package.
Yes when you go in another package, with child class object again you can access the member variable with default modifier.
might be this link will help you to understand more.Access modifier in java with example
Upvotes: 0
Reputation: 70584
The Java Language Specification writes:
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
...
A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
If the member or constructor is declared public, ....
Otherwise, if the member or constructor is declared protected, ...
Otherwise, if the member or constructor is declared private, ...
Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.
So it doesn't matter whether the access is from a subclass, all that matters is the package.
Since Class1
and Class2
are declared with default access, HelloWorld
must be in the same package with them in order to compile.
Upvotes: 2
Reputation: 41230
Look like both class(Class1 & Class2
) is in same package as well same class HelloWorld
it self and default modifier
is visible with in class or package.
default modifier
or no modifier
has significance in java, it is not same as private
and it's access level is well defined in documentation.
Upvotes: 5
Reputation: 649
It's whats known as package private. Any classes including sub-classes in the same package have access to the default modifier.
See extended answer at: In Java, difference between default, public, protected, and private
Upvotes: 1