Hosted Forum: West Visayas State University - Philippines > Object Oriented Programming with Java Class Forum

override versus overload

(1/1)

louiecerv:
This program shows how to override the default toString() method of objects.  It also shows how to create an equals() method to compare two objects.  You can find additional examples of the usage of the super keyword.


--- Code: ---
public class TestEmployee
{
public static void main(String[] args)
{
Employee janitor = new Employee();
System.out.println(janitor);

janitor.setName("Mike Enriquez");
janitor.setAnnualSalary(5000);
janitor.setYrHired(1999);
janitor.setSSN("99-19131-201");
System.out.println("janitor: ");
System.out.println(janitor);

Employee clerk = new Employee("Oscar Oida", 125000, 2000, "20-01011-019");
System.out.println("clerk: ");
System.out.println(clerk);

System.out.println("janitor.equals(clerk)= " +
janitor.equals(clerk) );
System.out.println("clerk.equals(clerk)= " +
clerk.equals(clerk));

}
}

--- End code ---

louiecerv:
The employee class


--- Code: ---
public class Employee extends Person
{

private double annualSalary;
private int yrHired;
private String SSN;

public Employee()
{
super();
annualSalary = 0f;
yrHired = 0;
SSN = "not defined";
}

public Employee(String name, double annualSalary,
int yrHired, String SSN)
{
super(name);
this.annualSalary = annualSalary;
this.yrHired = yrHired;
this.SSN = SSN;
}

/**
* mutator methods
*/
public void setAnnualSalary(double newSalary)
{
annualSalary = newSalary;
}

public void setYrHired(int newYrHired)
{
yrHired = newYrHired;
}

public void setSSN(String newSSN)
{
SSN = newSSN;
}

/**
* accessor methods
*/
public double getAnnualSalary()
{
return annualSalary;
}

public int getYrHired()
{
return yrHired;
}

public String getSSN()
{
return SSN;
}

public boolean equals(Object otherObject)
{
if (!(otherObject instanceof Employee))
{
return false;
}
else
{

Employee otherEmp = (Employee)otherObject;

return (this.sameName(otherEmp)
&& (this.annualSalary == otherEmp.annualSalary)
&& (this.yrHired == otherEmp.yrHired)
&& (this.SSN.equals(otherEmp.SSN)) );
}
}

public String toString()
{
System.out.println("Name          : " + super.getName());
System.out.println("Annual Salary : " + this.annualSalary);
System.out.println("Year  Hired   : " + this.yrHired);
System.out.println("SSN           : " + this.SSN);
return "";
}
}

--- End code ---

louiecerv:
Person Class


--- Code: ---
public class Person
{
private String name;

public Person()
{
name = "no name yet.";
}

public Person(String initialName)
{
name = initialName;
}

public void setName(String newName)
{
name = newName;
}

public String getName()
{
return name;
}

public void writeOutput()
{
System.out.println("Name: " + name);
}

public boolean sameName(Person otherPerson)
{
return ( this.name.equalsIgnoreCase(otherPerson.name) );
}
}

--- End code ---

Navigation

[0] Message Index

Go to full version