Java基类中超类的受保护方法会怎样? [英] What happens to protected method of a super class in base class in Java?

查看:52
本文介绍了Java基类中超类的受保护方法会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在package1中有一个A类,而Bpackage2中,它继承了A. A包含方法m1,它是protected.现在我的疑问是,当我在另一个也是package2的类C中创建B的对象时,B的对象无法访问方法m1为何?下面是我的代码

I have a A class in package1 and B is in package2 which inherits A. A contains method m1 which is protected. Now my doubt is when I create an object of B in another class C which is also package2, the object of B is unable to access method m1 why? Below is my code

package com.package1;

public class A {

    protected void m1(){
        System.out.println("I'm protectd method of A");
    }
}


package com.package2;

import com.package1.A;

public class B extends A {


    public static void main(String[] args) {

        B b = new B();
        b.m1();          // b object able to access m1

    }

}


package com.package2;

public class C {

    public static void main(String[] args) {

        System.out.println("Hi hello");
        B b = new B();
        b.m1(); //The method m1() from the type A is not visible

    }

}

超类的受保护方法在子类中是否私有?

Do protected method of super class become private in subclass?

推荐答案

来自

对象的受保护成员或构造函数只能从负责该对象实现的代码声明的包外部访问.

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

让C为声明受保护成员的类.只能在C的子类S的主体内进行访问.

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

方法 protected修饰符指定成员只能在其自己的程序包中(与package-private一样)访问,并且只能由该类在另一个程序包中的子类访问.

Means The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

来自控制对类成员的访问的Java文档

因此您可以从类B中访问方法m1,即使该方法不在同一程序包中也可以访问,因为它是A的子类.
但是您不能从类C访问方法m1,因为它既不在与A相同的程序包中,也不在其A的子类中.

So you can access method m1 from class B even its not on same package because it subclass of A.
But you can't access method m1 from class C because neither its in same package as A nor its subclass of A.

因此,要访问此方法,可以将方法m1公开或将类C移至与类A

So for accessing this method you can make method m1 public or move your class C into same package as class A

这篇关于Java基类中超类的受保护方法会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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