Can anybody explain me why do we need "protected" word? If I understand correctly,
default access: available in classes within the same package.
protected access: default access in same package + available to inherited classes (sub-classes) in any package. Basically, we get the same default access in same package.
So when should I use it? Just for the style of your code? To mark it that you are going to work with it from perspective of inheritance?
Thank you.
package firstPack;
public class First {
protected int a;
protected void Chat(){
System.out.println("Here I am");
}
}
package secondPack;
import firstPack.First;
public class Second extends First{
public static void main(String [] args){
First f=new First();
// f.Chat();
// System.out.println(f.a);
}
}
I used this code to test it. It didn't work.
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
).