1.Java访问权限修饰符
注:类和接口的访问方式 ,不能声明为private和protected
2. 演示protected的访问限制
包1:package com.protect.parent;
package com.protect.parent; //包1,声明父类
public class ParentDiffPack{
//声明属性和方法,均是protected
protected String name;
protected static int startc_age;
protected void run() {
System.out.println("父类可以跑。。。不是静态方法");
}
protected static void static_eat() {
System.out.println("父类可以吃。。。。静态方法");
}
}
包2:package com.protect.son;
package com.protect.son; //包2,声明子类
import com.protect.parent.ParentDiffPack; //导入父类的包(包1)
public class SonDiffPack extends ParentDiffPack {
public static void main(String[] args) {
//(static)不同包父类中静态属性和方法的调用方式既能实例化父类对象也可以直接用类名调用
ParentDiffPack parent = new ParentDiffPack();//---不同包的父类实例化:
parent.startc_age=12; //pass,但提示黄色should be accessed in a static way
parent.static_eat(); //pass,但提示黄色should be accessed in a static way
//(static)用类直接访问静态属性/方法
ParentDiffPack.startc_age=12;
ParentDiffPack.static_eat();
//parent.name="tom"; //报错,The field ParentDiffPack.name is not visible
//parent.run(); //报错,The method run() from the type ParentDiffPack is not visible
//this.name="tom"; //报错,Cannot use this in a static context
//(static)不同包父类中静态属性和非静态属性,静态方法和非静态方法都可以实例化子类对象进行调用。
SonDiffPack son = new SonDiffPack();//---不同包的子类实例化-----------------
son.name="xioaming";
son.startc_age=12; //pass,但提示黄色should be accessed in a static way
son.run();
son.static_eat(); //pass,但提示黄色should be accessed in a static way
//this.name="tom"; //报错,Cannot use this in a static context
//this.run(); //报错,Cannot use this in a static context
//(static)用类直接访问静态属性/方法
SonDiffPack.startc_age=20;
SonDiffPack.static_eat();
}
//不同包有继承关系的实例方法可以访问protect(static main 方法不能访问,因为静态方法是全局的、不属于对象的,没有this)
void test() {
this.name="tom";
this.run();
this.startc_age=22; //pass,但提示黄色should be accessed in a static way
this.static_eat(); //pass,但提示黄色should be accessed in a static way
}
}
//结论:protected声明的对象/方法在另一个包时:父类对象不能访问,子类对象可访问,非静态方法可访问