当一个方法设置一个类的属性,它被称为setter
方法:
public void setName(String name)
你可以使用这种方法通常不需要有返回类型只设置类的randomename
属性。但是如果你愿意,你肯定可以添加一个返回类型。如:
//this method will return true if the `randomname` was not set previously
//otherwise false
public boolean setName(String name) {
if (null == randomname) {
randomname = name;
return true;
}
else return false;
}
而且都setter方法,如果你能使用的方法,通常被称为getter
方法获取属性:
public String getName(String name)
话说方法用于打印randomname
属性。这是必须的,因为它是私有的,你不能打印randomname
外的类范围:
//this will print the value of randomname
public void saying()
//another scenario
voidvoid foo = new voidvoid() ;
foo.setName("Hello world") ;
//this line will generate an erro
System.out.println (foo.randomname) ;
//this will compile fine
foo.saying() ;
//you can also achieve the same result using getName
System.out.println (foo.getName()) ;
具有用于private
属性的setter/getter方法是mandatory
,如果你想retrieve/set
属性,但optional
为public
属性,但在我看来这是一个good practice
有它。
从setter方法返回'this'也是常见的,所以它们可以链接在一起。 –
好点,我错过了。 –