为什么受保护的修饰符在Java子类中的行为有所不同? [英] Why the protected modifier behave differently here in Java subclass?

查看:105
本文介绍了为什么受保护的修饰符在Java子类中的行为有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个不同的软件包中有以下两个类。我的实例方法的访问修饰符受到保护,这意味着相同或不同程序包中的任何子类都可以访问它吗?但是,在Eclipse中,我在第17行的子类 Cat 上看到以下消息

I have the following two class in two different packages. my access modifier for instance method is protected which means any subclass in same or different package has access to it right?. however, in Eclipse I see the following message on my subclass Cat on line 17

The method testInstanceMethod() from the type Animal is not visible 

我的上级和子类代码

package inheritance;

public class Animal {

    public static void testClassMethod() {
        System.out.println("The class" + " method in Animal.");
    }
    protected void testInstanceMethod() {
        System.out.println("The instance " + " method in Animal.");
    }
}

package testpackage;

import inheritance.Animal;

public class Cat extends Animal{
        public static void testClassMethod() {
            System.out.println("The class method" + " in Cat.");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method" + " in Cat.");
        }

        public static void main(String[] args) {
            Cat myCat = new Cat();
            Animal myAnimal = myCat;
            myAnimal.testClassMethod();
            myAnimal.testInstanceMethod();
        }
    }


推荐答案

受保护的访问修饰符不会授予 package 访问权限,这意味着同一软件包中的类不被授予对受保护字段的访问权限。

The protected access modifier does not grant package access meaning classes within the same package are not granted access to protected fields.

受保护并授予对包含该字段且位于同一包中的基类(继承关系)派生的类的访问权限。

Protected does grants access to classes derived from the base class (inheritance relationship) containing the field and that are in the same package.

因此,要满足保护级别的访问权限,必须满足两个条件:

So to satisfy protected level access two conditions must be met:


  1. 这些类必须位于同一包中。 / li>
  2. 必须存在继承关系。

在您的示例中,仅满足以下条件之一(这些类之间存在继承关系),但是它们不在同一个包中。

In your example only one of these conditions is satisfied (there is an inheritance relationship between the classes), however they are not in the same package.

如果您移动了 Animal Cat 放入同一程序包中。

If you moved Animal into the same package as Cat the code would compile.

package testpackage;

public class Animal {

    public static void testClassMethod() {
        System.out.println("The class" + " method in Animal.");
    }
    protected void testInstanceMethod() {
        System.out.println("The instance " + " method in Animal.");
    }
}

这篇关于为什么受保护的修饰符在Java子类中的行为有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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