简体   繁体   中英

Must extending class have the same access level as the class it extends

I want to extend a class that is declared public class A

It seems that if I want to create a Class B which extends class A, I must declare it with public modifier. Is it correct? I will be happy to get an explanation why I can't make access level "stronger" when extending a class?

I encounter this problem when I tried to extends the following class:

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

and when I extended VH , RecyclerView.ViewHolder with a class named : MyViewHolder that has private access I got a message saying: 'MyViewHolder has private access in ...'

Your code probably looks something like this:

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

The problem is that MyViewHolder is only accessible in MyAdapter 's body, not in its declaration. This can be worked around by making MyViewHolder package-private, so MyAdapter 's declaration can see it.

From the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM