首页 > 解决方案 > 访问控制练习 - java

问题描述

我需要通过在类终端中创建一个公共 hackCar 方法来打印 TestCar 类的属性。hackCar方法需要以一个TestCar为参数,打印TestCar的属性。这个任务的警告是我不能触及 TestCar 类中的任何东西。

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

故事课:

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";
}

谢谢!

标签: java

解决方案


私有字段被称为“私有”,因为没有办法获得它们。但是你可以为他们公开吸气剂:

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

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

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

对受保护的领域做同样的事情hasAirCondition

您的方法Terminal.getdoorUnlockCode()不能Terminal.getAirCondition()从另一个对象获取字段,它们必须在TestCar对象中


推荐阅读