0

An instance of a class, in Java, can access private fields of its own inner class, as the last line of code does, holder.textView , in the following listing:

   public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> {
       public static class PokedexViewHolder extends RecyclerView.ViewHolder {
           private LinearLayout containerView;
           private TextView textView;

           PokedexViewHolder(View view) {      
               super(view);
               containerView = view.findViewById(R.id.pokedex_row);
               textView = view.findViewById(R.id.pokedex_row_text_view);
           }
       }

       private List<Pokemon> pokemon = Arrays.asList(
               new Pokemon("Bulbasaur", 1),
               new Pokemon("Ivysaur", 2),
               new Pokemon("Venusaur", 3)
       );

       @Override
       public void onBindViewHolder(@NonNull PokedexViewHolder holder, int position) {
            Pokemon current = pokemon.get(position);
            holder.textView.setText(current.getName());
       }
   }
  • Better dupe target: https://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members – knittl Aug 14 '23 at 08:25

1 Answers1

0

An instance of a class can access private fields of its own type because Java's visibility rules allow nested classes to access private members of their enclosing class. In your example, PokedexViewHolder is an inner static class of PokedexAdapter, so it can access the private fields of PokedexAdapter. This encapsulation enables internal components to work together effectively within the same class.

  • I think this is not the best design out there. Because you could make a getter, or a setter, or make those fields public @tamtejszystan – Đạt Phạm Nguyễn Ngọc Aug 14 '23 at 08:22
  • @ĐạtPhạmNguyễnNgọc encapsulation exists for a reason, not for the sake of creating getters and setters. What reason do you see for an inner class to hide its implementation to its containing class. – Federico klez Culloca Aug 14 '23 at 08:26
  • Because private fields could not be access or modified outside of the class makes more sense to me. In this case, outside of the class mentioned but inside of its containing class. @FedericoklezCulloca – Đạt Phạm Nguyễn Ngọc Aug 14 '23 at 08:28