在java中使用方法,setter和getter

时间:2014-04-25 21:39:36

标签: java instantiation

我有这堂课:

public class Person
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String firstName = "Vasya";
    private String lastName = "Pupkin";
    private Integer age = 58;
    private Integer phone = 2;

    @Override
    public String toString() 
    {
        return "Person [firstName=" + firstName + ", lastName=" + lastName
                + ", age=" + age + "]";
    }

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

    public void setLastName(String lName)
    {
        lastName = lName;
    }

    public void setAge(Integer personAge)
    {
        age = personAge;
    }

    public void setPhone(Integer personPhone)
    {
        phone = personPhone;
    }

    public String getName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public Integer getAge()
    {
        return age;
    }

    public Integer getPhone()
    {
        return phone;
    }

    public void Init()
    {
        this.setName("");
        this.setLastName("");
        this.setPhone(0);
        this.setAge(0);
    }
}

我创建了一个变量:Person somePerson,然后我从该变量setName调用方法somePerson

somePerson.setName("");

但它会引发错误。

1 个答案:

答案 0 :(得分:4)

根据提供的代码,以下内容应该有效:

Person somePerson = new Person();
somePerson.setName("");

如果没有,那么其他事情正在发生。