Java 为什么另一个包中的子类不能访问受保护的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19949327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:45:54  来源:igfitidea点击:

Why subclass in another package cannot access a protected method?

javapackagesubclassprotectedmodifier

提问by user2986848

I have two classes in two different packages:

我在两个不同的包中有两个类:

package package1;

public class Class1 {
    public void tryMePublic() {
    }

    protected void tryMeProtected() {
    }
}


package package2;

import package1.Class1;

public class Class2 extends Class1 {
    doNow() {
        Class1 c = new Class1();
        c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
        tryMeProtected();  // No error
    }    
}

I can understand why there is no error in calling tryMeProtected()since Class2sees this method as it inherits from Class1.

我可以理解为什么调用没有错误,tryMeProtected()因为Class2看到这个方法是从Class1.

But why isn't it possible for an object of Class2to access this method on an object of Class1using c.tryMeProtected();?

但是为什么Class2一个对象不能在Class1using 对象上访问这个方法c.tryMeProtected();呢?

回答by Ankur Shanbhag

Protected methods can only be accessible through inheritance in subclasses outside the package. And hence the second approach tryMeProtected();works.

受保护的方法只能通过包外子类中的继承访问。因此第二种方法tryMeProtected();有效。

The code below wont compile because we are not calling the inherited version of protected method.

下面的代码无法编译,因为我们没有调用受保护方法的继承版本。

 Class1 c = new Class1();
 c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1

Follow this stackoverflowlink for more explaination.

按照此stackoverflow链接获取更多说明。

回答by Mik378

You use two different packages and you don't access your parent attributes by direct inheritance, but by an intermediate parent instance declared in the child class (similar to composition). => that's the not the way protectedworks.

您使用两个不同的包,并且不通过直接继承访问父属性,而是通过子类中声明的中间父实例(类似于组合)。=> 那不是工作的方式protected

Only direct inheritance allows protected parent's attributes to be reach.

只有直接继承才允许访问受保护的父级的属性。

Thus, you can do this:

因此,您可以这样做:

public class Class2 extends Class1 {
    doNow() {
        tryMeProtected();  // No error since direct inheritance 
    }    
}

but never this:

但从来没有这个:

public class Class2 extends Class1 {
    doNow() {
        Class1 c = new Class1();
        c.tryMeProtected(); // this is not a direct inheritance! since `c`, although a parent one is an intermediate instance created in the child instance. => bad
    }    
}

Indeed, this is a particularity of protectedkeyword often misunderstood.

的确,这是protected关键字的一个特殊性,经常被误解。

回答by Tushar D

As per Java Protected Access modifier definition methods which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

根据 Java Protected Access 修饰符定义,在超类中声明为 protected 的方法只能由其他包中的子类或受保护成员类的包中的任何类访问。

you can't access protected method by creating object of class. So for accessing Protected method you have to extend the superclass.(this explains your 2nd call is correct)

你不能通过创建类的对象来访问受保护的方法。因此,为了访问 Protected 方法,您必须扩展超类。(这说明您的第二次调用是正确的)

回答by Satyam

It can be acheived by two ways

可以通过两种方式实现

1. Either by making an object of Child class and then accessing the protected method of Parent class.

1. 要么通过创建子类的对象,然后访问父类的受保护方法。

PACKAGE 1

套餐一

public class Class1 {
    protected void m1() {
        System.out.println("m1 called");
    }
}

PACKAGE2

套餐2

public class Class2 extends Class1 {

    public static void main(String[] args) {
        Class2 class2 = new Class2();
        class2.m1();
    }
}

2. Or by directly calling the method from the Child class

2. 或者直接从Child类调用方法

eg tryMeProtected();

eg tryMeProtected();

回答by Anthony Raymond

I believe you misunderstand the difference between packageand protectedvisibility.

我相信你误解了可见性packageprotected可见性之间的区别。

package package1;

public class MyClass1 {
    public void tryMePublic() { System.out.println("I'm public"); }
    protected void tryMeProtected() { System.out.println("I'm protected"); }
    void tryMePackage() { System.out.println("I'm package"); }
}
  • tryMePublicwill be accessible wherever you are.
  • tryMeProtectedwill be accessible to every subclass AND every class in the same package.
  • tryMePackagewill be accessible to every class in the same package (not available in children class if they are in a different package)
  • tryMePublic无论您身在何处,都可以访问。
  • tryMeProtected每个子类和同一个包中的每个类都可以访问。
  • tryMePackage将可供同一包中的每个班级访问(如果子班级在不同的包中,则不可用)

Children class in the same package

同包儿童班

package package1;

public class Class2 extends MyClass1 {
    public void doNow() {
        tryMePublic(); // OK
        tryMeProtected(); // OK
        tryMePackage(); // OK
    }    
}

Children class in different package

不同套餐的儿童班

package package2;

import package1.MyClass1;

public class Class3 extends MyClass1 {
    public void doNow() {
        MyClass1 c = new MyClass1();
        c.tryMeProtected() // ERROR, because only public methods are allowed to be called on class instance, whereever you are
        tryMePublic(); // OK
        tryMeProtected(); // OK
        tryMePackage(); // ERROR
    }    
}

回答by Dewansh Nigam

First of all, you need to understand two things:

首先,你需要明白两件事:

1) The protectedmember functions of a class 'X' in package 'Y' can be accessed by the subclass i.e. a class that extends it (even if the subclass is in the package other than 'Y'). That is why,

1)protected包“Y”中类“X”的成员函数可以被子类访问,即扩展它的类(即使子类在“Y”以外的包中)。这就是为什么,

tryMeProtected(); // Showed no error because this was called by class 2 that is the subclass.

2) A protectedmember function of a class 'X' in package 'Y' cannot be accessed by itself if it is in other packages.

2)protected包“Y”中类“X”的成员函数如果在其他包中,则不能被自身访问。

[ A simple analogy: A bird that has its eggs kept in a nest 1 has flown to a nest 2. From the nest 2, it cannot access its egg kept in nest 1.] Similarly, a class cannot access its member function (unless public declared.) if it is in the other package.

[一个简单的类比:一只鸟的蛋保存在巢 1 中,它飞到了巢 2。从巢 2,它不能访问它保存在巢 1 中的蛋。] 同样,一个类不能访问它的成员函数(除非public 声明。)如果它在另一个包中。

That is why :

这就是为什么 :

c.tryMeProtected();  // Showed error because this was called by class 1 reference.
                     //  You can also think of it as class 1 cannot inherit itself.

回答by Nora alshareef

the protected modifier is 1.Package Private 2.can be seen by subclasses from other packages. now the key difference between :

protected 修饰符是 1.Package Private 2.可以被其他包的子类看到。现在之间的主要区别:

MyClass1 c = new MyClass1();
    c.tryMeProtected();

and

tryMyProtected(); 

is that the MyClass1 reference is used rather than inheritance. MyClass1 is in a different package and this code is not inheriting from MyClass1.

是使用 MyClass1 引用而不是继承。MyClass1 位于不同的包中,此代码不是从 MyClass1 继承的。