java - 扩展类必须与其扩展的类具有相同的访问级别

标签 java android inheritance

我想扩展一个声明为公共(public)类 A 的类

看来,如果我想创建一个扩展类 A 的B 类,我必须使用 public 修饰符声明它。这是对的吗? 我会很高兴得到一个解释,为什么我在扩展类(class)时不能使访问级别“更强”?

当我尝试扩展以下类时遇到此问题:

android.support.v7.widget.RecyclerView.Adapter<VH extends android.support.v7.widget.RecyclerView.ViewHolder>

当我使用具有私有(private)访问权限的名为 :MyViewHolder 的类扩展 VHRecyclerView.ViewHolder 时,我收到一条消息:< em>“MyViewHolder 在...中具有私有(private)访问权限”

最佳答案

您的代码可能如下所示:

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
    ...
    private class MyViewHolder extends RecyclerView.ViewHolder {
        ...
    }
    ...
}

问题是 MyViewHolder 只能在 MyAdapter 的主体中访问,而不能在其声明中访问。可以通过将 MyViewHolder 包设为私有(private)来解决此问题,这样 MyAdapter 的声明就可以看到它。

来自Java 8 Language Specification :

A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:

  • [descriptions of public, protected, and package access]
  • Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

关于java - 扩展类必须与其扩展的类具有相同的访问级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152758/

相关文章:

java - 使用 SSL 协议(protocol)的 AsyncHttpClient

android - Ant 构建在 Eclipse 中失败

android - android (Latha.ttf) 中泰米尔字体显示的字符不正确

android - 模拟 : Is there any way to call/run a real method with fake data.

java - Spring Boot中的Mockito不模拟对象

java - 关于挥杆程序的困惑

java - netty如何设置最大并发连接数

c++ - 为什么所有现有的 C++ 编译器都不支持继承构造函数?

C# 转换问题 : from IEnumerable to custom type

c++ - 使用基类指针调用带有派生类参数的模板化函数