Java受保护的访问不起作用 [英] Java Protected Access Not Working

查看:152
本文介绍了Java受保护的访问不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,有三种访问级别:

In java, there's three levels of access:


  • 公开 - 向世界开放

  • 私人 - 仅向班级开放

  • 受保护 - 仅对班级及其子类(继承)开放。

那么为什么java编译器会允许这种情况发生呢?

So why does the java compiler allow this to happen?

TestBlah.java:

TestBlah.java:

public class TestBlah {

    public static void main(String[] args) {
        Blah a = new Blah("Blah");
        Bloo b = new Bloo("Bloo");
        System.out.println(a.getMessage());
        System.out.println(b.getMessage()); //Works
        System.out.println(a.testing);
        System.out.println(b.testing); //Works
    }
}

Blah.java:

Blah.java:

public class Blah {
    protected String message;

    public Blah(String msg) {
        this.message = msg;
    }

    protected String getMessage(){
        return(this.message);
    }   
}

Bloo.java:

Bloo.java:

public class Bloo extends Blah {
    public Bloo(String testing) {
        super(testing);
    }
}


推荐答案

实际上它应该是:


仅对 同一个包上的类 类及其子类(继承)

Open only to the classes on the same package the class and its subclasses (inheritance)

这就是为什么

这篇关于Java受保护的访问不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆