我没有找到类似的问题,这是我注意到的参考,但没有帮助: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;
}
}
答案 0 :(得分:0)
此外,addContact()是静态方法。这意味着该方法属于该类而不是该类的实例。换句话说,所有CellPhone实例将共享列表static private List<String> myContacts
。在方法之前和列表之前删除静态变量,这将很有意义。
答案 1 :(得分:0)
我必须将CellPhone添加到列表中,然后才能进行设置。我认为数组比较容易,但是显然Arraylist是动态的。对于任何遇到我问题的人,这是我如何解决的问题。
jhr.myCellPhone.add(new cellPhone());
jhr.myCellPhone.get(0).addContact("Joseph");