- 一、封装的作用
- 二、封装的步骤
- 三、封装实例
首先来看枯燥的定义,封装是指一种将抽象性函式接口的实现细节包装、隐藏起来的方法。 一、封装的作用
二、封装的步骤封装可以保护本类的数据不被其他类随意访问
封装加强了代码的安全性
封装之后,修改自己的实现代码,而不用修改那些调用本来代码的程序
相信大家都被上边那些概念搞得很烦躁,接下来看看封装的实现步骤,相信大家就会对封装有一些了解了。
1、用 private修饰属性,示例代码如下:
class Animal {
private String name;
private int age;
private String color;
}
2、对每个变量提供对外的公共访问方法,也就是 getter():赋值 和 setter():取值 代码如下:
class Animal {
private String name;
private int age;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
三、封装实例
接下来我们看一个封装的实际程序例子,加深对封装的理解
class Animal {
private String name;
private int age;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
public class Test1 {
public static void main(String[] args) {
Animal a=new Animal();
a.setName("哈士奇");
a.setAge(1);
a.setColor("黑白相间");
System.out.println("我是一只"+a.getName()+"我今年"+a.getAge()+"岁啦!"+"我的颜色是"+a.getColor()+"的");
}
}



