java中封装encapsulate的概念
封装encapsulate的概念:就是把一部分属性和方法非公有化,从而控制谁可以访问他们。
本章源码
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
class Test3 {
int a; // default access访问
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
public class Test {
public static void main(String args[]) {
Test3 ob = new Test3();
// These are OK,a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error,错误
//ob.c = 100; // Error!, 因为c是私有变量
//你必须通过方法才能访问到c, You must access c through its methods
ob.setc(100); // OK
System.out.println("a,b,and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
输出结果:
a,b,and c: 10 20 100