java - 访问控制练习 - 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";
}
谢谢!
解决方案
私有字段被称为“私有”,因为没有办法获得它们。但是你可以为他们公开吸气剂:
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
对象中
推荐阅读
- python - 将嵌套字典转换为数据框,键作为行名,值中的字典作为列?
- command-line-interface - 使用 spaCy 命令行训练器管理训练/开发拆分
- arrays - 二维数组中的数组大小不匹配
- sql - PostgreSQL INSERT INTO 表不存在
- python - 关于python导入、函数、子目录的一个非常简单的问题
- java - SharedPreferences:为什么我的值没有被覆盖?
- graphql - 使用 request-promise 将数据发布到 graphql 服务器
- python - 重新采样 Python 熊猫排除某些字段
- excel - vba中的Instr不使用公式单元格
- php - 随着时间的推移,慢慢地用 Vue 替换 Laravel 刀片文件,但它变得混乱