我在这里有一个带有两个字符串的构造函数:
public class person
{
String first;
String last;
public person (String first, String last)
{
this.first = first;
this.last = last;
}
public String toString()
{
String result = first + "\n";
result += last + "\n";
return result;
}
}
创建构造函数的两个对象的主要方法:
import java.util.ArrayList;
public class k
{
public static void main (String[] args)
{
ArrayList<person> list = new ArrayList<person>();
person ken = new person ("Ken", "Smith");
person ben = new person ("Ben", "Smith");
list.add (ken);
list.add (ben);
System.out.println (list.get(0));
}
}
现在代码打印肯史密斯。我的问题是:我怎样才能打印出Ken而不是Ken Smith?
答案 0 :(得分:5)
按照惯例,Java类名称以大写字母开头。接下来,覆盖toString()
以打印两个名称。对于第一个名称,您需要添加一个getter(对于此示例,我还为姓氏添加了一个getter)
public class Person {
String first;
String last;
public Person(String first, String last) {
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String toString() {
String result = first + "\n";
result += last + "\n";
return result;
}
}
然后你可以用(main
)调用类似
System.out.println (list.get(0).getFirst());