Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问控制练习-java_Java - Fatal编程技术网

访问控制练习-java

访问控制练习-java,java,Java,我需要通过在类终端中创建一个公共hackCar方法来打印TestCar类的属性。hackCar方法需要将TestCar作为参数并打印TestCar的属性。这个作业的警告是,我不能接触TestCar类中的任何内容 我仍在努力打印TestCar中的两个私有属性。如何使用Test Car对象作为hackCar方法中的参数来打印Test Car类中的两个私有属性 故事类: class Story { public static void main(String args[]) {

我需要通过在类终端中创建一个公共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);
}
}


谢谢

私有字段称为“私有”,因为无法获取它们。但你可以为他们公开getter:

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

    public int getDoorUnlockCode() {
        return this.doorUnlockCode;
    }
}
然后在hackCar中改变方法 System.out.printlnother.doorUnlockCode;为此:System.out.printlnother.getDoorUnlockCode; 所以现在您可以通过公共getter访问字段doorUnlockCode

对受保护的现场空调执行相同的操作


您的方法Terminal.getdoorUnlockCode和Terminal.getAirCondition无法从另一个对象访问字段,它们必须位于TestCar对象中

,那么这里的实际问题是什么?是什么让您认为字段总是需要一个getter和setter方法?!是的:这不是家庭作业评估服务。请提出一个明确、具体的问题。请看我的东西,严格来说,没有任何字段的类中的getter方法也没有意义。您确定这些方法不属于您的TestCar类吗?这样做将允许您在终端的hackCar中调用other.hasAirCondition。。。Method为没有说得更具体而道歉。我对编程和这个社区都是新手,所以感谢您的耐心。我需要通过实现hackCar方法并使用TestCar作为参数来打印TestCar类中的属性。TestCar类是为了赋值而被限制的,所以它们不属于那里。感谢阿拉斯特,我应该注意到TestCar类是被限制的,所以我不能更改这些变量的访问修饰符。
class TestCar {
    // Your 4 fields here...

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