简体   繁体   中英

What's the correct way to handle abstract classes without using protected?

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?

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

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