java - 即使我已经扩展了类,为什么我不能访问 protected java 方法?

标签 java inheritance protected

这是 protected 方法的文档:

/** Converts jmusic score data into a MIDI Sequence */
protected  javax.sound.midi.Sequence scoreToSeq(Score score)

我创建了这个小类来扩展 scoreToSeq 方法来自的类:

public class MidiSequence extends MidiSynth{

    public Sequence getSequence(Score score){
        MidiSynth synth = new MidiSynth();
        Sequence sequence = null;
        try
        {
                    // Here I get the error saying that the method has
                    // protected access in MidiSynth
            sequence = synth.scoreToSeq(score);

        }
        catch (InvalidMidiDataException e)
        {
            /*
             *  In case of an exception, we dump the exception
             *  including the stack trace to the console.
             *  Then, we exit the program.
             */
            e.printStackTrace();
            System.exit(1);
        }

        return sequence;

    }
}

最佳答案

(编辑:theycallmemorty's answer 提供了实用建议,以避免在您的情况下出现此问题。此答案给出了您必须遵循该建议的原因,即为什么语言是这样设计的。)

您只能访问与访问代码(或子类)类型相同的另一个对象的 protected 成员 - 即使该成员在父类(super class)型中声明也是如此。

来自Java Language Specification, section 6.6.2 :

Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:

  • If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.
  • If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.

这是为了允许一个类型访问与它自己的继承树相关的成员,而不破坏其他类的封装。例如,假设我们有:

     A
    / \
   B   Other
  /
 C

并且 A 声明了一个 protected 成员 x。没有规则按它的方式工作,您可以通过将成员放在 Other 中来绕过封装:

public int getX(A a)
{
    return a.x;
}

并且只需调用传入 BC 的实例 - 该成员将有效地公开,因为您总是可以通过引入另一个类来解决它。 .不是一个好主意。根据当前规则,您必须子类化 BC - 您可能一开始就做不到。

关于java - 即使我已经扩展了类,为什么我不能访问 protected java 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1622219/

相关文章:

java - 访问父类(super class)构造函数中的局部变量

java - 无法访问实例化类的 protected 方法

java - Sun PKCS11 库 C_Encrypt 和 C_Decrypt 更改

c++ - 将 PIMPL 与单例和 auto_ptr 结合使用

java - Java 中 BigInteger 的问题

c++ - 全部继承自同一类的对象映射,调用对象方法而不是父类;由 小码哥发布于

android - 无法在 android (Android studio) 中测试 protected 方法

c++ - 错误 C2248 : cannot access protected member declared in class

java - 如何通过比较两个列表从一个列表中删除元素

java - Java Swing 使用哪种设计模式?