A:封装概述

  • 是指隐藏对象的属性和实现细节,仅对外提供公共访问方式。

    B:封装好处

  • 隐藏实现细节,提供公共的访问方式

  • 提高了代码的复用性
  • 提高安全性。

    C:封装原则

  • 将不需要对外提供的内容都隐藏起来。

  • 把属性隐藏,提供公共方法对其访问。
  1. class Demo3_Car {
  2. public static void main(String[] args) {
  3. //Car c1 = new Car();
  4. /*c1.color = "red";
  5. c1.num = 8;
  6. c1.run();*/
  7. //method(c1);
  8. method(new Car());
  9. //Car c2 = new Car();
  10. //method(c2);
  11. method(new Car()); //匿名对象可以当作参数传递
  12. }
  13. //抽取方法提高代码的复用性
  14. public static void method(Car cc) { //Car cc = new Car();
  15. cc.color = "red";
  16. cc.num = 8;
  17. cc.run();
  18. }
  19. }
  20. class Car {
  21. String color; //颜色
  22. int num; //轮胎数
  23. public void run() {
  24. System.out.println(color + "..." + num);
  25. }
  26. }