Java修饰符之protected的方法和变量(顺带static说明)(有道备份)

本文详细探讨了Java中访问权限修饰符的使用,特别是protected修饰符的访问限制。通过实例展示了不同包下父类和子类如何访问protected成员,包括属性、方法、静态属性和静态方法的访问方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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声明的对象/方法在另一个包时:父类对象不能访问,子类对象可访问,非静态方法可访问
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值