Well I was playing around with the program and I was able to access one of the Employee's class instance fields with the manager class.
Here is the code for the program.
Employee Class:
Code:
import java.util.*;
class Employee
{
public Employee(String aName, double aSalary, int year, int month, int day)
{
name = aName;
salary = aSalary;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public void raiseSalary(double byPercent)
{
double raise = this.salary * byPercent / 100;
this.salary += raise;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public String getName()
{
return name;
}
public int getID()
{
return id;
}
private int id;
private static int nextid = 1;
private final String name;
private double salary;
private Date hireDay;
{
id = nextid;
nextid +=2;
}
}
Manager Class:
Code:
import java.util.*;
class Manager extends Employee
{
/**
@param aName The employee's name
@param aSalary the salary
@param year the hire year
@param month the hire month
@param day the hire day
*/
public Manager(String aName, double aSalary, int year, int month, int day)
{
super(aName, aSalary, year, month, day);
bonus = 0;
}
public double getSalary()
{
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double b)
{
bonus = b;
}
private double bonus;
}
The program
Code:
import java.util.*;
public class StaffTest
{
public static void main(String myArgs[])
{
// Construct Manager Object
Manager boss = new Manager("Josh Stephens", 80000,2003,11,24);
boss.setBonus(5000);
// Fill Staff Array
Employee[] staff = new Employee[3];
staff[0] = boss;
staff[1] = new Employee("John Smith", 27000,2003,9,9);
staff[2] = new Employee("Tommy Tester", 40000, 2001, 3,15);
// Print out information
for(Employee e: staff)
{
System.out.println("name - " + e.getName() + " , Salary - $" + e.getSalary());
}
}
}
If I change The getSalary() method of the manager class to be just
Code:
getSalary()
{
return salary + bonus;
}
The program Errors out. But Why can I access the name field? They are both defined the same way.
Bookmarks