Problem with your test code is that you ware trying to access protected members of First
class instance and via First
class reference. Notice that since Second
class is not in the same package as First
one it doesn't have access to protected fields of any instance of base class, but have access to its own fields inherited from First
class (which includes protected
ones). So something like
First f = new First();
f.chat();//chat is protected in base class.
will not compile in Second
class, but something like
public void test() {
a = 1; // have access to inherited protected field or
chat(); // methods of base class
}
public static void main(String[] args) {
Second f = new Second();
f.chat();
System.out.println(f.a);
}
is OK since Second class have access to its inherited members.
Notice that code in main
method works only because it is placed inside Second
class since only derived classes or classes in the same package as First
have access to its protected members. So if this code will be placed inside other class like
class Test{
public static void main(String[] args) {
Second f = new Second();
f.chat();
System.out.println(f.a);
}
}
it will not compile (no access to protected members because Test
doesn't extend or is not in same package as First
).