java - 从另一个类调用非静态方法

标签 java static

我有两个类。 汽车服务员

public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
    this.staffNum = staffNum;
    this.id = id;
    this.available = available;
    this.name = name;
    this.assign = assign;
}

public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
    this.carID = carID;
    this.plateNum = plateNum;
    Cars.position = position;
    Cars.assignedTo = assignedTo;
    this.currTime = currTime;
}

我的助理是通过 for 循环创建的:

createIDList();
int staffAmount = getStaffAmount();

for (int x = 0; x < staffAmount; x++) {
    Attendant att = new Attendant(x + 1, Attendant.tempArray[x], true, attNm.getNm(), null);
    myAtt.add(att);
}
for (int x = 0; x < myAtt.size(); x++) {
    System.out.println(myAtt.get(x));
}

所有参数都来自从ArrayList获取它们的函数。所有服务员都有相同的名字。

汽车也是如此。 每次我创建一辆汽车时,它都来自一个函数,并且汽车将有自己的名称:car

创建后,我的服务员和我的汽车将添加到他们的 ArrayList 中(ArraylistCar 和 arraylistAtt)

但是当我创建新车时,所有汽车都输出相同的 ID,并且服务员的详细信息输出错误。

有人告诉我静态方法和变量是这个问题的原因。所以我尝试删除一些静态数据,但出现错误。 如果我使用 getID 方法删除静态,我将无法在服务类中调用它。 当我创建一个以方法作为参数的新类时,这些情况也会发生(这些方法不再是静态的,因此我无法从其他类中调用它们)。

请帮帮我,我被困住了。我知道这很长,我尝试了不同的方法但没有任何效果。 我还放置了我的 toString() 方法,以防它们出现问题。 有些人告诉我也把我的整个代码和输出放在下面,所以如果你需要的话,它完全在下面。

汽车:

@Override
public String toString() {
    return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId() 
    + "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}

服务员:

@Override
public String toString() {
    return "Attendant [staffNum=" + staffNum + ", id=" + id + ", available=" + available + ", name=" + name
            + ", Car=" + assign + "]";
}

PS:英语不是我的母语。

我的整个代码在这里:

public class Cars {

    private static String carID;
    private String plateNum;
    private static String position;
    private static Attendant assignedTo;
    private long currTime;
    static ArrayList<String> tempArray2 = new ArrayList<String>();

    public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
        this.carID = carID;
        this.plateNum = plateNum;
        Cars.position = position;
        Cars.assignedTo = assignedTo;
        this.currTime = currTime;
    }

    private static void createCarsID() {
        for (int x = 0; x < Garage.getCarsCapacity(); x++) {
            String tempCarID = ("CR" + (x + 1));
            tempArray2.add(tempCarID);
        }
    }

    public static String getID() {
        createCarsID();
        String tempID = null;
        String tempPos = null;
        for (int x = 0; x < Garage.getCarsCapacity(); x++) {
            if (tempArray2.get(x) != null) {
                tempID = tempArray2.get(x);
                tempPos = tempArray2.get(x);
                tempArray2.remove(tempArray2.get(x));
                getPos(tempPos);
                //tempArray2.get(x) = null;
                break;
            }
        }
        return tempID;
    }

    public static void getPos(String IdToPos) {
        String strPos = IdToPos.substring(2);
        int pos = Integer.parseInt(strPos);
        position = "GR" + pos;
    }

    public String getPlateNum() {
        return plateNum;
    }

    public static String getCarID() {
        return carID;
    }

    public static String getPosition() {
        return position;
    }

    public long getCurrTime() {
        return currTime;
    }
    public static Attendant getAssignedTo() {
        return assignedTo;
    }

    public static String askCarID() {
        boolean valid = false;
        System.out.println("Please enter your car's plate number.");
        Scanner scanCarID = new Scanner(System.in);
        String scannedCarID = scanCarID.nextLine();
        while (!valid) {
            if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
                valid = true;
                System.out.println(scannedCarID);
            } else {
                System.out.println("Please enter a valid plate number. Ex: AF 378");
                askCarID();
            }
        }
        return scannedCarID.toUpperCase();
    }

    public String convert(long miliSeconds) {
        ...
    }

    @Override
    public String toString() {
        return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId() 
        + "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
    }
}

.

public class Attendant {

    private static int staffAmount = 10;

    public int staffNum;
    private String id;
    private boolean available;
    private attNm name;
    private Cars assign;

    private String user;
    static String[] tempArray = new String[staffAmount];
    static ArrayList<Attendant> myAtt = new ArrayList<Attendant>();

    public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
        this.staffNum = staffNum;
        this.id = id;
        this.available = available;
        this.name = name;
        this.assign = assign;
    }

    public Attendant(String user) {
        this.user = user;
    }

    public static void createAtt() {
        createIDList();
        int staffAmount = getStaffAmount();

        Attendant att = null;
        for (int x = 0; x < staffAmount; x++) {
            att = new Attendant(x + 1, Attendant.tempArray[x], true, attNm.getNm(), null);
            myAtt.add(att);
        }

        for (int x = 0; x < myAtt.size(); x++) {
            System.out.println(myAtt.get(x));
        }
    }

    public static void startWork() {
        createAtt();
    }

    public static Attendant askForAtt() {
        Scanner scanAtt = new Scanner(System.in);
        Random randAtt = new Random();
        //Attendant  asnAtt = null;
        System.out.println("Do you require an Attendant ? Y or N");
        String response = scanAtt.next();
        if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y"))) {
            // Cars.setAssignedTo(myAtt.get(randAtt.nextInt(myAtt.size())));
            Attendant attendant = myAtt.get(randAtt.nextInt(myAtt.size()));
            while(!attendant.isAvailable()){
                attendant = myAtt.get(randAtt.nextInt(myAtt.size()));
            }
            return attendant;

        } else if ((response.equals("n")) || (response.equals("no")) || (response.equals("No")) || (response.equals("N"))) {
            return new Attendant ("User");
        }
        return new Attendant ("User");    //If input is neither Yes nor No then return new Attendant    
    }

    public static void assignCarAtt(){

    }

    public int getStaffNum() {
        return staffNum;
    }

    public static int getStaffAmount() {
        return staffAmount;
    }

    public void setStaffNum(int staffNum) {
        this.staffNum = staffNum;
    }

    public void setAvailable(boolean available) {
        this.available = available;
    }

    public boolean getAvailable(){
        return available;
    }

    public void setAssign(Cars assign) {
        this.assign = assign;
    }

    public String getId() {
        return id;
    }

    public boolean isAvailable() {
        return available;
    }

    public attNm getName() {
        return name;
    }

    public static void createIDList() {
        for (int x = 0; x < staffAmount; x++) {
            tempArray[x] = ("Att" + (x + 1));
        }
    }

    public String strAssignAttCar(Cars assign){
        String result = null;
        if(assign!=null){
            result = Cars.getCarID();
        }
        return result;
    }

    @Override
    public String toString() {
        return "Attendant [staffNum=" + staffNum + ", id=" + id + ", available=" + available + ", name=" + name
                + ", Car=" + assign + "]";
    }

}

车库类打印;

  Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att10(Ava) Parked at:18:32:08, Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
   // Should have been like that:
    Car:HU 457 ID:CR1 Position:GR1 Assigned to:Att10(Ava) Parked at:18:32:08, Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]

服务员类(class)打印;

    Attendant [staffNum=9, id=Att9, available=false, name=Elizabeth, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
    Attendant [staffNum=10, id=Att10, available=false, name=Ava, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att10(Ava) Parked at:18:32:08]
   // Should have been like that:
    Attendant [staffNum=9, id=Att9, available=false, name=Elizabeth, Car=Car:HU 457 ID:CR2 Position:GR2 Assigned to:Att9(Elizabeth) Parked at:18:32:21]
    Attendant [staffNum=10, id=Att10, available=false, name=Ava, Car=Car:HU 457 ID:CR1 Position:GR1 Assigned to:Att10(Ava) Parked at:18:32:08]

最佳答案

首先,将 Cars 类设为单数(即 Car)更有意义。

背景信息:在语句 Cars car1 = new Cars() 中,Cars 是类,car1汽车类。这个问题是由于混淆了两者而引起的。

静态变量/方法不与该类的任何特定实例关联;它只与类相关。因此,当您将 carID 声明为 static 时,您就表示只有一个全局 Cars.carID,而不是多个 car1.carIDcar2.carID 等。确保实例变量/方法不是静态的。

删除 static 关键字时遇到的问题是因为您调用的是 Cars.getCarID() 而不是 car1.getCarID().您需要将类上的所有方法调用更改为类的实例上的方法调用。

tl;dr:要解决此问题,请删除所有 static 关键字,并将对 Cars.getCarID() 等方法的所有静态引用更改为 car1.getCarID ().

面向对象编程的示例(注意,除了 main 方法之外,没有静态方法或变量):

汽车.java:

class Car {
    int id;
    int speed;

    Car(int id, int speed) {
        this.id = id;
        this.speed = speed;
    }

    int getSpeed() {
        return speed;
    }

    void setSpeed(int newSpeed) {
        speed = newSpeed;
    }

    int getId() {
        return id;
    }

    void goFast() {
        System.out.println("VROOM! This car is going so fast: " + speed);
    }
}

Person.java:

class Person {
    Car myCar;
    int id;

    Person(int id, Car car) {
        this.id = id;
        this.myCar = car;
    }

    int getCar() {
        return myCar;
    }

    int getId() {
        return id;
    }

    void floorIt() {
        myCar.setSpeed(myCar.getSpeed() + 10);

    void drive() {
        myCar.goFast();
    }
}

Main.java:

class Main {
    public static void main(String[] args) {
        Car ferrari = new Car(1, 1000);
        Car bmw = new Car(2, 500);

        Person alice = new Person(1, ferrari);
        Person bobby = new Person(2, bmw);

        alice.drive();
        bobby.drive();

        bobby.floorIt();
        bobby.drive();

    }
}

关于java - 从另一个类调用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39648620/

相关文章:

java - Spring批处理不将作业实例插入数据库

java - 从@Test注释TestNG获取字符串

具有固定边框的 Java GUI Jlabel

c# - 在构造函数以外的地方构建结构/对象

java - Java中静态方法可以调用实例方法吗

java - 在 Java 中解密 linux encfs(标准配置,192 位 aes)

static - Visual C++下dllimport/dllexport及静态库编译

python - Python中的私有(private)构造函数

java - 在 android Activity 中调用静态处理程序上的 post

C# 静态库