java中封装encapsulate的概念

封装encapsulate的概念:就是把一部分属性和方法非公有化,从而控制谁可以访问他们。 https://blog.csdn.net/qq_44639795/article/details/101847882

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());
}
}

更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44639795/article/details/101847882

posted @ 2021-01-13 09:45  师徒行者  阅读(194)  评论(0编辑  收藏  举报