温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java超类中的protected成员如何访问

发布时间:2025-07-28 20:49:01 来源:亿速云 阅读:109 作者:小樊 栏目:编程语言

在Java中,protected成员可以在同一个包中的其他类以及不同包中的子类中访问。以下是如何访问超类中的protected成员的示例:

  1. 同一个包中的其他类:

如果两个类位于同一个包中,你可以直接访问超类中的protected成员。例如,假设我们有一个名为SuperClass的超类,它具有一个protected成员变量protectedVar和一个protected方法protectedMethod()。

package com.example;

public class SuperClass {
    protected String protectedVar = "I am a protected variable";

    protected void protectedMethod() {
        System.out.println("I am a protected method");
    }
}

在同一包中的另一个类SamePackageClass中,你可以直接访问这些protected成员:

package com.example;

public class SamePackageClass extends SuperClass {
    public void accessProtectedMembers() {
        System.out.println(protectedVar); // 直接访问protected成员变量
        protectedMethod(); // 直接访问protected方法
    }
}
  1. 不同包中的子类:

如果子类位于不同的包中,你需要使用super关键字来访问超类中的protected成员。例如,假设我们有一个名为OtherPackageSubClass的子类,它位于com.other包中。

package com.other;

import com.example.SuperClass;

public class OtherPackageSubClass extends SuperClass {
    public void accessProtectedMembers() {
        System.out.println(super.protectedVar); // 使用super关键字访问protected成员变量
        super.protectedMethod(); // 使用super关键字访问protected方法
    }
}

请注意,如果你尝试在不同包中的非子类中访问protected成员,编译器将报错,因为protected访问修饰符不允许这种访问。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手