gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:31:47 25 4
gpt4 key购买 nike

我想扩展一个声明为公共(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, ora constructor of a class type, is accessible only if the type isaccessible 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 levelclass (§7.6) that encloses the declaration of the member orconstructor.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com