Reputation:
public class Doubt1{
public static void main(String[] args){
Manager m1 = new Manager(25000);
Manager m2 = new Manager(25000);``
System.out.println(m1.getSalary(250000) + " " + m2.getSalary()); //how is m1.getSalary working when getSalary(int) is protected in Employee class
}
}
class Employee{
protected int salary;
public Employee(int s){
salary = s;
}
protected int getSalary(int s){
return salary + s;
}
}
class Manager extends Employee{
public Manager(int s){
super(s);
}
public int getSalary(){
return salary;
}
}
I have overloaded getSalary method from Employee class in manager class. getSalaray(int) method of Employee class has protected access and hence, can only be accessed from Manager class. But when I call m1.getSalary(25000), why is the compiler not complaining about "protected access in employee class" as it does when I declare the method private? Or is protected access modifier something else than what I assume it to be?
Upvotes: 0
Views: 132
Reputation: 32323
protected
method allows access by other members of the same package
, in addition to subclasses that are not in the same package.
Access Levels Chart:
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Read more in the Oracle tutorial
Upvotes: 2
Reputation: 2219
The protected
access modifier allows more forms of access than private
. Because the method is in the same package or subclass, the access is allowed.
More info here http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Upvotes: 3