Hej,
Mam taki kod:
class Employee
{
public String name;
public int salary;
private String address;
// 1 constructor
public Employee(String name)
{
this(name, 0);
}
// 2 constructor
public Employee(String name, int sal)
{
this(name, sal, null);
}
// 3 constructor
public Employee(String name, int sal, String addr)
{
this.address = name;
this.salary = sal;
this.address = addr;
}
//getters setters
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
//toString
@Override
public String toString()
{
StringBuilder constructor3 = new StringBuilder();
constructor3.append(this.getName()).append(this.getSalary()).append(this.getAddress());
String constructor3ToString = constructor3.toString();
StringBuilder constructor2 = new StringBuilder();
constructor2.append(this.getName()).append(this.getSalary());
String constructor2ToString = constructor2.toString();
StringBuilder constructor1 = new StringBuilder();
constructor1.append(this.getName());
String constructor1ToString = constructor1.toString();
if (this.getAddress().equals(null) && this.getSalary() == 0)
{
return constructor1ToString;
}
else if (this.getAddress().equals(null))
{
return constructor2ToString;
}
else
{
return constructor3ToString;
}
}
}
Gdy podaję:
Employee employee = new Employee("Jane");
System.out.println(employee);
To wyrzuca:
Exception in thread "main" java.lang.NullPointerException
at Employee.toString(Employee.java:79)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at ExercisesApp.main(ExercisesApp.java:10)
Chciałem mieć 3 konstruktory i tylko podawać parametry, a potem przy drukowaniu , żebym otrzymał tylko podaną wartość jak przesłałem do kontsruktora przy tworzeniu obiektu,
ale zgubiłem się w tych konstruktorach.
Ktoś pomoże?
Pozdrawiam