我想扩展一个声明为公共(public)类 A 的类
看来,如果我想创建一个扩展类 A 的B 类,我必须使用 public 修饰符声明它。这是对的吗? 我会很高兴得到一个解释,为什么我在扩展类(class)时不能使访问级别“更强”?
当我尝试扩展以下类时遇到此问题:
android.support.v7.widget.RecyclerView.Adapter<VH extends android.support.v7.widget.RecyclerView.ViewHolder>
当我使用具有私有(private)访问权限的名为 :MyViewHolder 的类扩展 VH、RecyclerView.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/