gpt4 book ai didi

Java继承——从父类获取参数

转载 作者:行者123 更新时间:2023-12-02 07:38:58 25 4
gpt4 key购买 nike

我想从 Car 的父类中获取一个参数并将其添加到我的数组 (carsParked),我该怎么做?

父类

public class Car
{
protected String regNo; //Car registration number
protected String owner; //Name of the owner
protected String carColor;

/** Creates a Car object
* @param rNo - registration number
* @param own - name of the owner
**/
public Car (String rNo, String own, String carColour)
{
regNo = rNo;
owner = own;
carColor = carColour;
}

/** @return The car registration number
**/
public String getRegNo()
{
return regNo;
}

/** @return A String representation of the car details
**/
public String getAsString()
{
return "Car: " + regNo + "\nColor: " + carColor;

}
public String getColor()
{
return carColor;
}
}

子类

public class Carpark extends Car
{
private String location; // Location of the Car Park
private int capacity; // Capacity of the Car Park - how many cars it can hold
private int carsIn; // Number of cars currently in the Car Park
private String[] carsParked;

/** Constructor for Carparks
* @param loc - the Location of the Carpark
* @param cap - the Capacity of the Carpark
*/
public Carpark (String locations, int room)
{

location = locations;
capacity = room;
}
/** Records entry of a car into the car park */
public void driveIn()
{
carsIn = carsIn + 1;



}

/** Records the departure of a car from the car park */
public void driveOut()
{
carsIn = carsIn - 1;
}

/** Returns a String representation of information about the carpark */
public String getAsString()
{
return location + "\nCapacity: " + capacity +
" Currently parked: " + carsIn +
"\n*************************\n";
}

}

最后一题法

public String getCarsByColor (String carColour)

{

  for (int num = 0; num < carsParked.length; num++)
{
if ( carColour.equals(carsParked[num]) )
{
System.out.print (carsParked[num]);
        }
}
return carColour;

}

到目前为止,如果在参数中输入“red”,它会列出所有红色的汽车及其相应的信息,但似乎不起作用 ~_~。

最佳答案

您在这里的关系似乎有误: parking 场不是汽车。我建议不要在这些类之间的任何方向上使用继承。和 Carpark应该只有一组或一组汽车。

还要注意参数 carsIn没有必要 - 只需获取 length汽车阵列(或 size() 如果它是 Collection )。

编辑: 好吧,忽略继承部分,似乎在 driveIn 时添加汽车是有意义的被调用,并在 driveOut 时删除它们被称为。

driveIn可能应该采取 Car作为参数,因此该方法可以访问您要存储的参数(我个人只存储 Car 引用,但没问题)。因为我们要添加和删除这些参数,所以使用 List 会容易得多。可以调整自身大小而不是数组,例如 ArrayList .例如:

private final List<String> carsRegNosParked = new ArrayList<String>();

public void driveIn(Car car) {
carsRegNosParked.add(car.getRegNo());
}

不太清楚 driveOut 是什么应该做。可能需要特定的注册号才能删除:

public void driveOut(String regNo) {
carsRegNosParked.remove(regNo);
}

或者它可以不分青红皂白地删除一辆车,比如添加的第一辆车:

public void driveOut() {
if (!carsRegNosParked.isEmpty()) {
carsRegNosParked.remove(0);
}
}

注意 remove(Object) 之间的区别和 remove(int) .

关于Java继承——从父类获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com