1

I have a base class fragment (as shown below). I extend this class in 3 other fragment classes, each of which share the same EditText that needs to be accessed in these 3 fragments. For this reason, I have the EditText variable set up in the base class (so I don't have to call it 3 times, once in each fragment).

Should this variable be public or should it be private with a getter method set up? Why?

Here is my base class fragment:

public abstract class BaseFragment extends Fragment {
    public EditText editText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(getFragmentLayout(), container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        editText = (EditText) view.findViewById(R.id.editText);
    }

    protected abstract int getFragmentLayout();
}
  • private methods/fields are cannot be. You can use protected instead...inherited.http://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private?rq=1 – Shadab Faiz Mar 18 '17 at 16:41

2 Answers2

0

If you are only accessing it from BaseFragment and its child classes, it can be Protected. This will restrict access to only itself and classes that extend it.

protected EditText editText;

See this document for more details about accessibility.

Carl Poole
  • 1,970
  • 2
  • 23
  • 28
0

If editText is going to be used by sub classes of BaseFragment class then you need to mark it as protected.

Here's the javadoc, this is what is says:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

By doing this, sub classes won't need to use getters and setters methods to access this property. They will be able to use it as if it was defined in those classes only. However, for any class that is not in BaseFragment's package or doesn't extend BaseFragment, this property will be private.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102