Overload and hide methods in Java

后端 未结 4 1840
离开以前
离开以前 2021-02-05 14:39

i have an abstract class BaseClass with a public insert() method:

public abstract class BaseClass {

 public void insert(Object object) {
  // Do so         


        
4条回答
  •  不知归路
    2021-02-05 15:15

    As Cletus points out, this is really a design problem, in that you are trying to create a child class that does not obey the contract of its parent class.

    There are rare circumstances where working around this by e.g. throwing an exception might be desirable (or at least an acceptable compromise -- for example, the Java Collections Framework) but in general it's a sign of poor design.

    You may wish to read up on the Liskov substitution principle: the idea that (as Wikipedia puts it) "if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program". By overriding a method to throw an exception, or hiding it any other way, you're violating this principle.

    If the contract of the base class' method was "inserts the current object, or throws an exception" (see e.g. the JavaDoc for Collection.add()) then you could argue you're not violating LSP, but if that is unexpected by most callers you may want to rethink your design on these grounds.

提交回复
热议问题