繁体   English   中英

Java无法访问静态公共方法

[英]Java can't access static public method

我没有找到类似的问题,这是我注意到的参考,但没有帮助: 从Scala访问公共静态Java方法

我对为什么无法从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;
}
}

另外,addContact()是静态方法。 这意味着该方法属于该类而不是该类的实例。 换句话说,所有CellPhone实例都将共享列表static private List<String> myContacts 在方法之前和列表之前删除静态变量,这将很有意义。

我必须将CellPhone添加到列表中,然后进行设置。 我认为数组比较容易,但是显然Arraylist是动态的。 对于任何遇到我问题的人,这就是我如何解决的。

    jhr.myCellPhone.add(new cellPhone());
    jhr.myCellPhone.get(0).addContact("Joseph");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM