【发布时间】:2018-10-27 17:41:35
【问题描述】:
我没有找到类似的问题,这是我注意到但没有帮助的参考:Accessing public static java method from scala
我很困惑为什么我不能从 Start 类访问 cellPhone 方法 addContact? addContact 是公共的和静态的。如果您查看 joseph 类,我想了解对象数组与对象 ArrayList 在访问方面的区别。
我知道这是完美组织的,也许我应该在 Joseph 类中加入 cellPhone 类?但这也不起作用。
我的错误出现在 Start 类中。
开始上课:
public class Start
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Joseph jhr = new Joseph();
jhr.addCreditCard("Visa");
jhr.setWeight(168);
jhr.setHairColor("Brown");
jhr.setGender("male");
jhr.setName("Randy ");
jhr.myCellPhone.addContact();//ERROR: he method addContact() is undefined for the type List<cellPhone>
jhr.cell[0].setCellPhone(5255857);
jhr.cell[1].setCellPhone(4155053);
jhr.cell[0].addContact("Bob");
jhr.cell[1].addContact("Amy");
//jhr.cell.addContact("Nameishi");
//jhr.cell.setCellPhone(3333847);
System.out.println("Single : "+jhr.showStatus() + " Gender: " + jhr.showGender() +" Name:"+jhr.showName());
//System.out.println("Cell number: " +jhr.cell.showCellNumber());
System.out.println("Middle name: " + jhr.middleName);
}
}
手机类:
public class cellPhone {
private int cellPhoneNumber;
static private List<String> myContacts = new ArrayList<String>(100);
public cellPhone() {
// TODO Auto-generated constructor stub
}
//show all numbers in cell phone
public final int showCellNumber() {
return cellPhoneNumber;
}
//get all Contacts in cell Phone
public List<String> contactsList()
{
return myContacts;
}
//add numbers to cell phone
public void setCellPhone(int myNumber) {
cellPhoneNumber = myNumber;
}
//add contacts to cell phone
static public void addContact(String contact) {
myContacts.add(contact);
}
}
约瑟夫类:
public class Joseph extends human
{
//public static final cellPhone cell = null;
public cellPhone [] cell = new cellPhone[2];
static public List<cellPhone> myCellPhone = new ArrayList<cellPhone>(100);
public String middleName;
private int weight;
public Joseph()
{
middleName = "John";
weight = 0;
cell[0]= new cellPhone();
cell[1]= new cellPhone();
//cell.setCellPhone(3253847);
}
public void setWeight(int setw)
{
weight = setw;
}
public int getWeight()
{
return weight;
}
}
【问题讨论】:
-
报错信息很清楚了吧?再读一遍:“List
类型的方法 addContact() 未定义”。因此,您尝试在 jhr.myCellPhone上致电addContact()。jhr.myCellPhone的类型为List<cellPhone>。 List 没有任何名为addContact的方法,正如它的 javadoc 所示:docs.oracle.com/javase/8/docs/api/java/util/List.html。请尊重 Java 命名约定:类以大写字母开头。 -
因为它是静态的,你最好直接调用
cellPhone.addContact并且请使用带有大写字母的开始类名 -
不,这绝对不是我说的。 addContact 是 CellPhone 类的一个方法。因此使用它(或者至少应该使用它,如果它不是静态的,这是另一个错误)将联系人添加到手机。您无法将联系人添加到手机列表中,但这就是您正在尝试做的事情。
-
所以我的逻辑/设计是错误的。我应该让列表只存在于 CellPhone 对象中?
-
@Nameishi 我建议你研究一下basics of Java。您似乎缺少一些关于类、对象和静态方法的重要知识。
标签: java list inheritance arraylist