您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,protected
是一个访问修饰符,它可以用于类、方法和变量。当一个类的成员(包括类、方法或变量)被声明为protected
时,它具有以下特性:
protected
成员。这意味着,如果一个类和声明为protected
的成员在同一个包中,那么这些类可以直接访问这些成员,就像它们是public
的一样。protected
成员。这意味着,如果一个类继承了一个包含protected
成员的父类,并且这个子类和父类不在同一个包中,那么子类可以访问父类中的protected
成员。需要注意的是,protected
访问修饰符不能用于顶层类(即不是内部类或嵌套类的类)。顶层类只能使用public
或默认(无修饰符)访问修饰符。
以下是一个简单的示例,展示了protected
访问修饰符的用法:
// 文件名:ProtectedExample.java
package com.example;
public class ProtectedExample {
// protected变量
protected int protectedVar = 10;
// protected方法
protected void protectedMethod() {
System.out.println("This is a protected method.");
}
}
// 文件名:SubClassExample.java
package com.example.subclass;
import com.example.ProtectedExample;
public class SubClassExample extends ProtectedExample {
public void accessProtectedMembers() {
// 在子类中访问protected变量
System.out.println("Protected variable value: " + protectedVar);
// 在子类中调用protected方法
protectedMethod();
}
}
// 文件名:Main.java
package com.example.main;
import com.example.subclass.SubClassExample;
public class Main {
public static void main(String[] args) {
SubClassExample subClassExample = new SubClassExample();
subClassExample.accessProtectedMembers();
}
}
在这个示例中,ProtectedExample
类包含一个protected
变量和一个protected
方法。SubClassExample
是ProtectedExample
的子类,位于不同的包中。在SubClassExample
类中,我们可以直接访问protected
变量和调用protected
方法。最后,在Main
类中,我们创建了SubClassExample
的实例并调用了accessProtectedMembers
方法,以展示如何访问protected
成员。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。