简体   繁体   中英

How not to override a method in a subclass in Java?

I have a class that will be needed to create derived classes with similar functionality.

public abstract class PreloaderAdapter<T> extends BaseAdapter {
    private final List<T> mList;

    ...
    public void addItems(List<T> list) {
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void clear(boolean isRepaint) {
        mList.clear();
        if (isRepaint) {
            notifyDataSetChanged();
        }
    }
    ...
}

In derived classes I can override those methods but don't want, as they are the same.

  1. Can you, please, say me, will it be enough to write so?

     public class SomeListAdapter extends PreloaderAdapter<MyClass> { private final List<MyClass> mList; ... public void addItems(List<MyClass> list) { super.addItems(list); // mList.addAll(list); // notifyDataSetChanged(); } public void clear(boolean isRepaint) { super.clear(isRepaint); // mList.clear(); // if (isRepaint) { // notifyDataSetChanged(); // } } ... } 

Or should I uncomment these lines and delete them in a superclass?

  1. Should I make a superclass as abstract?

  2. Should I use fields inside a superclass?

In Java, if a method is declared and implemented at a superclass, if you extend this superclass, the subclass will have that method implemented by default.

eg

public class Dog {
    //Atributes
    //Methods
    public void bark() {...}//Do an action

}

public class PitBull extends Dog {
    //Atributes
    //Methods
    public void action2() {...}//Do another action
}

With this code, you can do this:

   PitBull dogObject = new PitBull();
   dogObject.bark();
  1. By default the methods are inherited, that is, they will be avaible to be used, so you don't have to override them.
  2. The superclass should be abstract if you are interested in not to give the possibility to create instances of this class or leave some behaviour without implementation and the duty of being implemented by a subclass.
  3. You can use fields in the superclass, there's no problem. In any case, pay attention to the visibility (private, protected, public).

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