gpt4 book ai didi

java - 访问控制练习 - java

转载 作者:行者123 更新时间:2023-12-02 11:01:22 27 4
gpt4 key购买 nike

我需要通过在类 Terminal 中创建公共(public) hackCar 方法来打印 TestCar 类的属性。 hackCar方法需要接受一个TestCar作为参数,并打印TestCar的属性。这项作业的警告是我不能接触 TestCar 类中的任何内容。

我仍在努力打印 TestCar 中的两个私有(private)属性。如何使用 Test Car 对象作为 hackCar 方法中的参数来打印 Test Car 类中的两个私有(private)属性?

故事课:

class Story {
public static void main(String args[]) {
TestCar testCar = new TestCar();
Terminal terminal = new Terminal();
terminal.hackCar(testCar);
}
}

类终端{

 public void hackCar(TestCar other) {

System.out.println(other.doorUnlockCode);

System.out.println(other.hasAirCondition);

System.out.println(other.brand);

System.out.println(other.licensePlate);
}

}

class TestCar {

private int doorUnlockCode = 602413;
protected boolean hasAirCondition = false;
String brand = "TurboCarCompany";
public String licensePlate = "PHP-600";
}

谢谢!

最佳答案

私有(private)字段被称为“私有(private)”,因为没有办法获取它们。但你可以为它们创建公共(public) getter:

class TestCar {
// Your 4 fields here...

public int getDoorUnlockCode() {
return this.doorUnlockCode;
}
}

然后在hackCar方法中进行更改System.out.println(other.doorUnlockCode); 改为: System.out.println(other.getDoorUnlockCode());现在您可以通过公共(public) getter 访问字段 doorUnlockCode

对 protected 字段执行相同操作hasAirCondition

您的方法 Terminal.getdoorUnlockCode()Terminal.getAirCondition() 无法从另一个对象获取字段,它们必须位于 TestCar对象

关于java - 访问控制练习 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305186/

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