In this example we will see object manipulation i.e. for example Comparing two objects.
This example will demonstrate simple payroll system.
- Create folder with name “payroll”
- Create class “Employee” in payroll folder which will have logic to calculate salary for Employee.
- Now come out of the payroll folder. And create ObjMethTest class to test the code.
Employee.java
package payroll;
public class Employee{
private int id;
float rate;
protected int hours;
private static int count;
public Employee(int h, float r){
id = 101 + count++;
hours = h;
rate = r;
}
public Employee(){
this(0, 50);
}
public Employee(int i, int h, float r){
id = i;
hours = h;
rate = r;
}
public int getHours(){
return hours;
}
public void setHours(int value){
hours = value;
}
public float getRate(){
return rate;
}
public void setRate(float value){
rate = value;
}
public int getId(){
return id;
}
public double getNetIncome(){
double income = hours * rate;
int ot = hours - 180;
if(ot > 0)
income += 50 * ot;
return income;
}
public static int countEmployees(){
return count;
}
public int hashCode(){
return id;
}
public boolean equals(Object other){
if(other instanceof Employee){
Employee that = (Employee) other;
return (id == that.id) && (hours == that.hours) && (rate == that.rate);
}
return false;
}
public String toString(){
return id + " " + hours + " " + rate;
}
public void finalize(){
System.out.printf("Employee:%d finalized%n", id);
}
}
ObjMethTest.java
import payroll.Employee;
class ObjMethTest{
public static void main(String[] args){
Employee a = new Employee(175, 75);
Employee b = a;
Employee c = new Employee(101, 175, 75);
Employee d = new Employee();
System.out.printf("a is identical to b: %b%n", a == b);
System.out.printf("a is identical to c: %b%n", a == c);
System.out.printf("Hash-code of a: %d%n", a.hashCode());
System.out.printf("Hash-code of b: %d%n", b.hashCode());
System.out.printf("Hash-code of c: %d%n", c.hashCode());
System.out.printf("a is equal to b: %b%n", a.equals(b));
System.out.printf("a is equal to c: %b%n", a.equals(c));
System.out.printf("a: %s%n", a);
System.out.printf("b: %s%n", b);
System.out.printf("c: %s%n", c);
d = null;
System.gc();
}
}
To compile:
javac ObjMethTest.java
To run:
java ObjMethTest
No comments:
Post a Comment