1.
2.
3.
4.
1.
2.
3.
super
1.
2.
3.
2。
1.
2.
3.
写个demo测试一下
父类
复制收展Javapackage com.test.clas;
/**
* @Desc -累行客
* @Author luolei
* @Web http://www.leixingke.com/
* @Date 2020/08/07 08:47
*/
public class SuperClass {
protected String protectedField="父类 protected 变量";
protected void protectedMethod(){
System.out.println("父类 protected 方法");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
子类中调用父类protected方法或成员变量
复制收展Javapackage com.test.clas.protect;
import com.test.clas.SuperClass;
/**
* @Desc -累行客
* @Author luolei
* @Web http://www.leixingke.com/
* @Date 2020/08/07 08:50
* @总结protected访问权限
* 1. 不能通过父类SuperClass对象实例访问父类的protected方法或成员变量,在子类InvokeSuperMethod中也是不可以的。
* 2. 子类中可以通过子类InvokeSuperMethod对象实例调用父类SuperClass的protected方法或成员变量。
* 3. 子类中可以通过super调用父类SuperClass的protected方法或成员变量。
* 4. 非子类中无论如何是不能调用一个类的protected方法或成员变量,实例化子类也是不可以的。
*
*/
public class InvokeSuperMethod extends SuperClass {
public static void main(String[] args) {
InvokeSuperMethod invokeSuperMethod = new InvokeSuperMethod();
invokeSuperMethod.protectedMethod();
System.out.println(invokeSuperMethod.protectedField);
invokeSuperMethod.method();
}
public void method(){
super.protectedMethod();
System.out.println(super.protectedField);
/*SuperClass superClass = new SuperClass();
//编译错误
superClass.protectedMethod();
//编译错误
System.out.println(superClass.protectedField);*/
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
普通类中实例化子类调用父类protected方法或成员变量
复制收展Javapackage com.test.clas.protect;
/**
* @Desc -累行客
* @Author luolei
* @Web http://www.leixingke.com/
* @Date 2020/08/07 09:53
*/
public class InvokeProtected {
public static void main(String[] args) {
//3在不同包非子类中通过实例化子类,通过子类实例访问父类的protected方法或成员变量,是不行的。
InvokeSuperMethod invokeSuperMethod = new InvokeSuperMethod();
//编译失败
/*invokeSuperMethod.protectedMethod();
System.out.println(invokeSuperMethod.protectedField);*/
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20