封装:将类的某些信息隐藏在类内部,不允许外部程序直接访问,而是通过该类的提供的方法实现对隐藏信息的操作访问。
好处: 1、只能通过规定方法访问数据
2、隐藏类的实现细节
3、方便加入控制语句
4、方便修改实现
如何使用封装:
1修改属性的可见性-----设为private
2创建共有的getter和setter方法----用于属性的读写
3在getter和setter方法中加入属性控制语句------对属性值的合法性进行进行判断
通过代码我们来了解一下(这个代码没有控制语句,有需要的可以在getter和setter方法中加入)
public class Classtext {
private String type;
private String color;
public void setType(String c){
this.type=c;
}
public void setColor(String a){
this.color=a;
}
public String getType(){
return type;
}
public String getColor(){
return color;
}
public String function(String b){
return "播放"+b;
}
}
在测试类去实现
public class Classtextmain {
public static void main(String[]args){
Classtext thing=new Classtext();
thing.setType("华硕A550C");
thing.setColor("红色");
String re=thing.getType();
System.out.println(re);
String re1=thing.getColor();
System.out.println(re1);
String re2= thing.function("电影");
System.out.println(re2);
}
}
很简单的封装代码。希望对需要的人有所帮助的。
this 关键字的用法
1 this 调用属性
eg:
this,health=100;
this,name="大黄";
2调用方法
this.print();
3调用构造方法
this()
this(参数)
注:如果使用,必须是构造方法的第一条语句