码迷,mamicode.com
首页 > 编程语言 > 详细

[Thinking in Java]修饰符public,protected,默认,private

时间:2015-04-26 06:57:15      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

在使用Java时,常常会遇到四种修饰符,即public,protected,默认(没有修饰符),private,这里写下它们的区别public :包内包外任意访问

protected :包内访问,包外仅子类访问

默认 :包内任意访问

private :仅类内访问

用代码解释

技术分享
 1 package p1;
 2 import static java.lang.System.*;
 3 
 4 public class A {
 5     public int m1 = 1;
 6     protected int m2 = 2;
 7     int m3 = 3;
 8     private int m4 = 4;
 9     
10     public void f1() {
11         out.println("f1");
12     }
13     protected void f2() {
14         out.println("f2");
15     }
16     void f3() {
17         out.println("f3");
18     }
19     private void f4() {
20         out.println("f4");
21     }
22     
23     void demo() {
24         out.println(m1);
25         out.println(m2);
26         out.println(m3);
27         out.println(m4);
28         
29         f1();f2();f3();f4();
30         
31         B b = new B();
32     }
33     
34     public static void main(String[] args) {
35         new A().demo();
36     }
37 }
38 
39 class B {
40     public B() {
41         out.println("class B");
42     }
43 }
p1.A
技术分享
 1 package p1;
 2 import static java.lang.System.*;
 3 
 4 public class C {
 5     void demo() {
 6         A a = new A();
 7         out.println(a.m1);
 8         out.println(a.m2);
 9         out.println(a.m3);
10         //out.println(a.m4);
11         
12         a.f1();a.f2();a.f3();
13         //a.f4();
14         
15         //默认类可以在同一个包内使用
16         B b = new B();
17     }
18     
19     public static void main(String[] args) {
20         new C().demo();
21     }
22 }
p1.C
技术分享
package p2;
import p1.*;
import static java.lang.System.*;

public class D {
    void demo() {
        A a = new A();
        out.println(a.m1);
        //以下都无法访问
        //out.println(a.m2);
        //out.println(a.m3);
        //out.println(a.m4);
        
        a.f1();
        //以下都无法调用
        //a.f2();
        //a.f3();
        //a.f4();
        
        //默认类不能在其它包内使用
        //B b = new B();
    }
    
    public static void main(String[] args) {
        new D().demo();
        E.main(args);
    }
}

class E extends A{//A的子类
    void demo() {
        out.println(m1);
        out.println(super.m1);
        out.println(new A().m1);
        
        out.println(m2);
        out.println(super.m2);
        //out.println(new A().m2);//失败
        //out.println(a.m3);
        //out.println(a.m4);
        
        f1();
        f2();
        super.f2();
        //new A().f2();//失败
        //a.f3();
        //a.f4();
        
        //默认类不能在其它包内使用
        //B b = new B();
    }
    
    public static void main(String[] args) {
        new E().demo();
    }
}
p1.D

 

[Thinking in Java]修饰符public,protected,默认,private

标签:

原文地址:http://www.cnblogs.com/cyninma/p/4457223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!