java受保护的方法可访问性 [英] java protected method accessibility

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

问题描述

在下面的代码中,消费者类可以访问父类的受保护方法.由于父类和消费者类之间没有关系,这怎么可能.请解释

In the below code the Consumer class can access the protected method of Parent class.How is it possible since there is no relation between Parent and Consumer class.Please explain

class Parent {
    public void method1(){
        System.out.println("PUBLIC METHOD");
    }
    private void method2(){
        System.out.println("PRIVATE METHOD");
    }
    protected void method3(){
        System.out.println("PROTECTED METHOD");
    }
}

public class Consumer {
    public static void main(String[] args){
        Parent parentObj = new Parent();
        parentObj.method1();
        //parentObj.method2();
        parentObj.method3();
    }
}

谢谢

推荐答案

protected表示:相同的程序包或通过继承.由于您的课程都在default package中(在现实生活中不建议使用),因此protected启用访问.顺便说一句:如果您尝试测试Java访问控制,您会忘记default access(default access =无修饰符= package private).

protected means: same package or by inheritance. Since your classes are both in the default package (not recommended in real life), protected enables access. By the way: if you tried to test java access control, you forgot default access (default access = no modifier = package private).

private访问意味着:除了该特定类(以及仍为主机类成员的非静态内部类)之外,无处可访问.

private access on the other hand means: access from nowhere except this particular class (and non-static inner classes, which are still member of the host-class).

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

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