1、对属性进行封装,使用户不能直接输入数据,我们需要避免用户再使用对象.属性的方式对属性进行赋值。则需要将属性声明为私有的(private).
2、我们将类的属性私有化(private),同时,提供公共的(public)方法来获取(getxxx)和设置(setxxx)此属性的值
封装性的体现,需要权限修饰符来配合
1.java规定的4种权限(从小到大排列):private、缺省、protected 、public
2.这4种权限可以用来修饰类及类的内部结构:属性、方法、构造器、内部类
3.具体的,4种权限都可以用来修饰类的内部结构:属性、方法、构造器、内部类
修饰类的话,只能使用:缺省、public
例:
package kindmethod3;public class privatetest {// 用private修饰,定义为私有变量,外不不能随意更改 private int age; //年龄 private string name; //名字// 同时,我们给这两个属性创建两个可以更改他们的接口 public void setage(int age){ this.age=age; } public int getage(){ return age; } public void setname(string name){ this.name=name; } public string getname(){ return name; } public void display(){ system.out.println("我的名字叫"+name+"今年"+age+"岁"); }}
package kindmethod3;public class privatetest1 { public static void main(string[] args) { privatetest sc = new privatetest();// 这个时候就不能直接给类中属性直接赋值了,就会报错// sc.age=18;// sc.name="小芳"// 我们需要通过set方法给属性赋值,get取值 sc.setage(18); sc.setname("小芳"); sc.display(); }}
一下代码查看运行结果:
public class order { private int text1; int text2; public int text3; private void methodprivate(){ text1 = 1; text2 = 2; text3 = 3; } void methoddefault(){ text1 = 1; text2 = 2; text3 = 3; } public void methodpublic(){ text1 = 1; text2 = 2; text3 = 3; }}
public class ordertest { public static void main(string[] args) { order order = new order(); order.text2 = 1; order.text3 = 2; //出了order类之后,私有的结构就不可以调用了// order.text1 = 3;//the field order.text1 is not visible order.methoddefault(); order.methodpublic(); //出了order类之后,私有的结构就不可以调用了// order.methodprivate();//the method methodprivate() from the type order is not visible }}
以上就是java封装及权限修饰符应用实例分析的详细内容。
