java simple perception in four access modifiers

The four access modifiers are (private by default protected public) access to this sort by the size of the (small to large)

Test 1: This category is performed

package Demo1;
public class Test {
private void show1(){
System.out.println("show1 private");
}

void show2(){
System.out.println("show2 默认");
}

protected void show3(){
System.out.println("show3 protected");
}
public void show4(){
System.out.println("show4 public");
}

public static void main(String[] args) {
Test test = new Test();
test.show1();
test.show2();
test.show3();
test.show4();
}
}
输出结果

show1 private
show2 默认
show3 protected
show4 public

The results showed that: In this class, the four modifier modified methods are accessible.

Test 2: the same package class

package Demo1;
class Test2 {public 
public static void main (String [] args) {
the Test Test new new = the Test ();
test.show1 ();
test.show2 ();
test.show3 ();
test.show4 ();
}
}
error : java: show1 () is the private access control Demo1.Test
the test.show1 (); commented
package Demo1;
public class Test2 {
public static void main(String[] args) {
Test test = new Test();
// test.show1();
test.show2();
test.show3();
test.show4();
}
}
结果

show2 default
show3 protected
show4 public

In the sub-category

package Demo1;
Son the extends the Test class {public 
public static void main (String [] args) {
the Test Test new new = the Test ();
// test.show1 ();
test.show2 ();
test.show3 ();
test.show4 () ;
}
}
with the same results of the implementation test1

results show that: under the same package type, except for private use can not be called a modified rest could be called.

Test 3: class in different packages
Demo2 Package; 

Import Demo1.Test;

public class Son the extends the Test {
public static void main (String [] args) {
the Test Test new new = the Test (); // other classes in different packages
// test.show1 ();
/ / test.show2 ();
// test.show3 ();
test.show4 ();
System.out.println ( "-----------");
Son Son = Son new new (); // subclasses in different packages
// son.show1 ();
// son.show2 ();
son.show3 ();
son.show4 ();
}
}
results

show4 public
-----------
show3 protected
show4 public

The results show that: under different subclasses package may call (protected, public), can only call other classes (public) in different packages

to sum up:

1. Private : emphasize their use in this class;

2. Default : emphasize the use of the package in the same class;

3. protected : emphasize the use by subclasses;

4. public: stressed that everyone can use;

Guess you like

Origin www.cnblogs.com/qingfengdream/p/11306551.html