Suppose I have a class name Employee
class Employee
{
int empID;
String name;
public Employee(int empID,String name)
{
this.empID = empID;
this.name = name;
}
// getters and setters
}
Now I create subclass based on their position
class Manager extends Employee
{
private String salary;
private int deptID;
public Manager(String salary, int deptID,int id, String name)
{
super(id,name);
this.salary = salary;
this.deptID = deptID;
}
// getters and setters
}
If I want to access the empID and name of Manager from Manager class, how can I do that as those fields are private? I was thinking in the getter function in Manager class ,I would do super.getName() and super.getID()?
If there is anything wrong in class design pattern, please let me know. I want to make it as perfect as it can be. Thanks for help.
If you use protected variables they can be accessed by any class that inherits them.
class Employee
{
protected int empID;
protected String name;
public Employee(int empID,String name)
{
this.empID = empID;
this.name = name;
}
}
class Manager extends Employee
{
private String salary;
private int deptID;
public Manager(String salary, int deptID,int id, String name)
{
super(id,name);
this.salary = salary;
this.deptID = deptID;
// Can access protected variables
empID = 0;
}
}
Otherwise you can use getters and setters with the protected or public accessor with your variables being marked as private.
Currently your variables are marked as default (no specified accessor) you can see what the different accessor allow you to do here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html