猿问

Java无法访问静态公共方法

我没有找到类似的问题,这是我注意到但没有帮助的参考: Accessing public static java method from scala


我很困惑为什么我不能从 Start 类访问 cellPhone 方法 addContact?addContact 是公共和静态的。如果您查看 joseph 类,我想了解对象数组与对象 ArrayList 在访问方面的区别。


我知道这是完美的组织,也许我应该在约瑟夫课上有手机课?但这也不起作用。


我的错误在 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);

}



}


拉丁的传说
浏览 372回答 2
2回答

收到一只叮咚

我必须将手机添加到列表中,然后我必须设置它。我认为数组更容易,但显然 Arraylist 是动态的。对于任何有我问题的人来说,我是如何解决它的。&nbsp;&nbsp;&nbsp;&nbsp;jhr.myCellPhone.add(new&nbsp;cellPhone()); &nbsp;&nbsp;&nbsp;&nbsp;jhr.myCellPhone.get(0).addContact("Joseph");

慕姐8265434

此外, addContact() 是一个静态方法。这意味着该方法属于类而不是类的实例。换句话说,所有 CellPhone 实例都将共享 list&nbsp;static private List<String> &nbsp;myContacts。删除方法之前和列表之前的静态,这一切都有意义。
随时随地看视频慕课网APP

相关分类

Java
我要回答