在 Java 中,是否可以调用同级 class 的受保护方法,其中同级具有不同的类型参数?

In Java is it possible to call a sibling class's protected method where the sibling has different type parameters?

给出以下 parent class:

public class AbstractParent<T> {
    abstract protected void doSomething();
}

和以下 child class:

public class DelegatingChildClass<T,U> extends AbstractParent<T> {
   AbstractParent<U> delegate;
   public DelegatingChildClass(AbstractParent<U> delegate) {
      this.delegate = delegate;
   }

   @Override
   protected void doSomething() {
      delegate.doSomething();//<--- Problem line
   }
}

我对受保护方法的理解是,访问仅限于:

由于 DelegatingChildClass 扩展了 AbstractParent,我期望委托的 doSomething() 方法可以访问。但是编译器抱怨它具有受保护的访问权限。这是编译器错误吗?还是我对受保护的访问修饰符应该如何工作有错误的理解?

"classes that extend the declaring class" 意味着您可以沿着该对象的扩展层次结构访问同一对象 (this) 的超级 class 中的方法。 DelegatingChildClass<T,U> 类型的对象也是 AbstractParent<T> 类型的对象,因此在 DelegatingChildClass<T,U> 的代码中,您可以对同一对象使用 AbstractParent<T> 的方法。这将允许 super.doSomething(),但它在这里没有意义,因为 super.doSomething()abstract

使用 delegate 在这里调用 doSomething() 是不可能的,因为类型 DelegatingChildClass<T,U> 的对象不会在这里扩展变量 delegate 中的对象。这种用法称为组合,而不是扩展。