面向对象的三大特征——封装、继承、多态(&常用关键字)
一、封装 Encapsulation
在面向对象程式设计方法中,封装是指,一种将抽象性函式接口的实作细节部份包装、隐藏起来的方法。
封装的概念(针对服务器开发,保护内部,确保服务器不出现问题)
将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类提供的方法来实现对隐藏信息的操作和访问(用private进行封装)
封装的优点
1、只能通过规定方法访问
2、隐藏类的实现细节
3、方便加入控制语句
4、方便修改实现
实现封装的步骤
1. 修改属性的可见性来限制对属性的访问(一般限制为private),例如:
public class Person { private String name; private int age; }
这段代码中,将 name 和 age 属性设置为私有的,只能本类才能访问,其他类都访问不了,如此就对信息进行了隐藏。
2. 对每个值属性提供对外的公共方法访问,也就是创建一对赋取值方法,用于对私有属性的访问,例如:
public class Person{ private String name; private int age; public int getAge(){ return age; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } }
采用 this 关键字是为了解决实例变量(private String name)和局部变量(setName(String name)中的name变量)之间发生的同名的冲突。
实例
1 package com.jredu.ch11;
2 //品牌,型号,颜色,时速; 方法包括:启动,停止
3 public class Car {
4 private String brand;
5 private String type;
6 private String color;
7 private String speed;
8
9 public Car(String brand, String type, String color, String speed) {
10 super();
11 this.brand = brand;
12 this.type = type;
13 this.color = color;
14 this.speed = speed;
15 }
16 public Car() {
17 super();
18 }
19 public Car(String brand, String type, String color) {
20 super();
21 this.brand = brand;
22 this.type = type;
23 this.color = color;
24 }
25
26
27 public String start(){
28 return getColor()+getBrand()+getType()+"启动";
29 }
30 public String stop(){
31 return getColor()+getBrand()+getType()+"停止,该时速可达"+getSpeed();
32 }
33 public String getBrand() {
34 return brand;
35 }
36 public void setBrand(String brand) {
37 this.brand = brand;
38 }
39 public String getType() {
40 return type;
41 }
42 public void setType(String type) {
43 this.type = type;
44 }
45 public String getColor() {
46 return color;
47 }
48 public void setColor(String color) {
49 this.color = color;
50 }
51 public String getSpeed() {
52 return speed;
53 }
54 public void setSpeed(String speed) {
55 this.speed = speed;
56 }
57
58
59 }
以上实例中public方法是外部类访问该类成员变量的入口。
通常情况下,这些方法被称为get和set方法。
因此,任何要访问类中私有成员变量的类都要通过这些getter和setter方法。
测试类代码
1 package com.jredu.ch11;
2
3 public class CarTest {
4 public static void main(String[] args) {
5 Car car=new Car();
6 car.setBrand("宝马");
7 car.setType("M6");
8 car.setColor("蓝色");
9 car.setSpeed("370km/h");
10 System.out.println(car.getColor()+car.getBrand()+car.getType()+"启动");
11 Car car1=new Car("奔驰", "SEL100", "红色的");
12 System.out.println(car1.start());
13 Car car2=new Car("奥迪","A8","黑色","300km/h");
14 System.out.println(car2.stop());
15 }
16 }
以上代码编译运行结果如下:











浙公网安备 33010602011771号