I’m trying to implement a constructor in Java and I don’t know if I’m doing something wrong, but I keep getting garbage outputs.
This is the variable I’m trying to assign values to:
private static Employee employee;
This is how I’m trying to assign it:
employee = new Employee(empType, empFName, empLName, empBDate, empGender, empHireDate, empReleaseDate, empBaseSalary);
And here is the class and constructor:
public class Employee {
private String Type;
private String FName;
private String LName;
private Date BDate;
private String Gender;
private Date HireDate;
private Date ReleaseDate;
private double BaseSalary;
public Employee(String type, String fname, String lname, String bdate, String gender, String hire, String release, double salary){
this.Type = type;
this.FName = fname.toUpperCase();
this.LName = lname.toUpperCase();
this.BDate = new Date(bdate);
this.Gender = gender;
this.HireDate = new Date(hire);
if (release == "null"){
this.ReleaseDate = null;
}
else if(release != "null"){
this.ReleaseDate = new Date(release);
}
this.BaseSalary = salary;
}
}
When I try to print, just to test it, this is how I’m printing it:
System.out.println(employee);
And this is what I get every time:
Employee@4c264dd8
Could someone tell me what i’m doing wrong?
3
Java doesn’t know anything about how you want an object printed unless you tell it what to do by implementing toString()
. If you don’t, it will default to Object.toString()
to get a string representation of your object. Object.toString()
returns
getClass().getName() + '@' + Integer.toHexString(hashCode())
which explains the output you’re seeing.
If you print Object in Java ,it will print class Name with Hexadecimal value.
If you want your own thing you have to override toString().
public void toString()
{
//print here this.Type +":"+ this.FName for fields you want.
}
Every Java Object comes with a toString() method. You will have to override it to get the desired output.I believe hashCode of the object (memory address) is being printed!
From the Object.toString() docs:
Returns a string representation of the object. In general, the
toString method returns a string that “textually represents” this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `@’, and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Therefore, you must provide your own toString method by doing this:
@Override
public void toString(){ return myString; }