初识封装
初识封装
封装,即隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读取和修改的访问级别。
|
访问权限修饰符 |
||||
|
修饰符 |
同一个类 |
同一个包 |
子类 |
所有类 |
|
Private |
* |
|
|
|
|
Default |
* |
* |
|
|
|
Protected |
* |
* |
* |
|
|
Public |
* |
* |
* |
* |
注:关于Protected的两个细节:
1、 若父类和子类在同一个包中,子类可访问父类的Protected成员,也可访问父类对象的Protected成员。
2、 若子类和父类不在同一个包中,子类可访问父类的Protected成员,但不可访问父类对象的Protected成员。
1 package com.sanyuan.encupsulation; 2 3 public class Person { 4 private int testPrivate = 100; 5 int testDefault = 200; 6 protected int testProtected = 300; 7 8 public void test(){ 9 System.out.println(this.testPrivate); 10 System.out.println(this.testDefault); 11 } 12 13 }
1 package com.sanyuan.encupsulation; 2 3 public class Student extends Person{ 4 5 public void test(){ 6 System.out.println(super.testProtected); 7 } 8 9 public static void main(String[] args) { 10 Person p = new Person(); 11 //p.testPrivate; 12 System.out.println(p.testDefault); 13 System.out.println(p.testProtected); 14 } 15 16 }
1 package a; 2 3 import com.sanyuan.encupsulation.Person; 4 5 public class Teacher extends Person{ 6 7 public void test(){ 8 System.out.println(super.testProtected); 9 //System.out.println(super.testDefault); 10 } 11 12 public static void main(String[] args) { 13 Person p = new Person(); 14 //System.out.println(p.testProtected); 15 } 16 17 }
浙公网安备 33010602011771号