CoolMind
CoolMind

Reputation: 28773

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?

Upvotes: 0

Views: 85

Answers (2)

Rub&#233;n Ballester
Rub&#233;n Ballester

Reputation: 111

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.

e.g

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();

Upvotes: 1

jperis
jperis

Reputation: 300

  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).

Upvotes: 1

Related Questions