1

For example:

public abstract class SomeBaseClass extends Fragment {
   protected static final String INT_TAG = "int_tag";
   protected int someInt;

   //...
}

public class ChildClass extends SomeBaseClass {
    public static ChildClass newInstance(int argInt) {
        Bundle args = new Bundle();
        bundle.putInt(INT_TAG, argInt);
        ChildClass fragment = new ChildClass();
        fragment.setArgs(args);
        return fragment;
    }

    public void onCreate() {
        someInt = getArguments().getInt(INT_TAG);
    }

    //...
}

However I've heard that it's a bad idea to use protected variables in abstract classes for some reason (I don't know why). What's the alternative?

KaliMa
  • 1,970
  • 6
  • 26
  • 51
  • 1
    protected member variables violate the main principle of OOP: encapsulation (aka information hiding). But simply setting them private and adding (protected) getter/setter methods doesn't change it. Also Inheritance is often misused for code reuse by declaring variables in the (abstract) base class that really belong to the extending classes just to not needing to declare them in each and every child class. So the best I can say is: always declare your variables `private` in that class that is really using them. – Timothy Truckle Nov 21 '16 at 22:12
  • @TimothyTruckle Abstract class and private does not work together well – Vasu Nov 21 '16 at 22:25
  • @javaguy for me it works out perfectly. – Timothy Truckle Nov 21 '16 at 22:27
  • Awesome discussion here http://softwareengineering.stackexchange.com/questions/162643/why-is-clean-code-suggesting-avoiding-protected-variables – Pravin Sonawane Nov 30 '16 at 04:37

1 Answers1

0

It's a bad idea to access protected attributes because it breaks the encapsulation, making your strongly coupled. Still, you can access your protected fields using getters and setters.

References

Community
  • 1
  • 1