【问题标题】:Hiding methods with a subclass parameter隐藏带有子类参数的方法
【发布时间】:2011-08-24 23:24:55
【问题描述】:

不确定这是否称为“方法隐藏”或“方法覆盖”,或者两者都不是,并且希望获得一些关于该主题的好文章。尤其是它是否是好的做法,何时以及何时不使用它,以及使用它的优点/缺点。

public class Animal {

  /* constructor */
  Animal () { }

  /* instance method */
  void add(Number n) {
    System.out.println("An animal added a number!");
  }

  /* Main method */
  public static void main(String[] args) {
    Integer i = 2;   // Integer i = new Integer(2);
    Double d = 3.14; // Double d = new Double(3.14);

    Animal mammal = new Animal();
    Cat tom = new Cat();
    Mouse jerry = new Mouse();

    mammal.add(i); // produces "An animal added a number!"
    mammal.add(d); // produces "An animal added a number!"

    tom.add(i);    // produces "Tom added an integer!"
    tom.add(d);    // produces "An animal added a number!"

    jerry.add(i);  // produces "An animal added a number!"
    jerry.add(d);  // produces "Jerry added a double!"
  }
}

class Cat extends Animal {

  /* constructor */
  Cat () { }

  /* instance method */
  void add(Integer i) {
    // param of type Integer extends Number
    System.out.println("Tom added an integer!");
  }
}

class Mouse extends Animal {

  /* constructor */
  Mouse () { }

  /* instance method */
  void add(Double d) {
    // param of type Double extends Number
    System.out.println("Jerry added a double!");
  }
}

编辑:

感谢@MByD,发现这被称为“方法重载”。

与上述相关的新问题: 在Animal 类中,我想创建一个采用Number 对象并使用子类CatMouse 中的重载add() 方法之一的方法。有没有比下面显示的更好的方法来做到这一点?

public class Animal {
...
  void subtract(Number n) {
    if      (n instanceof Integer) this.add(-(Integer) n); // from the Cat class
    else if (n instanceof Double)  this.add(-(Double) n);  // from the Mouse class
    ...
  }
...
}

是的,我意识到我可以写this.add(-n),但我想知道是否有办法根据参数的子类来选择实现。由于参数是抽象类型,无法实例化,我必须传递一个子类作为参数。

【问题讨论】:

    标签: java methods parameters overloading


    【解决方案1】:

    这称为方法重载,因为方法的签名不相同。

    Java Tutorials of methods

    Java 编程语言支持重载方法,而 Java 可以区分具有不同方法签名的方法。这 意味着类中的方法可以具有相同的名称,如果它们有 不同的参数列表(对此有一些限制条件 将在标题为“接口和继承”的课程中讨论)。

    是否以及何时使用各种重载/覆盖/阴影等的争论是一个很大的问题。一个非常好的资源是书Effective Java,由 Joshua Bloch 撰写。我发现这非常有用和有趣。

    【讨论】:

    • 好吧,我想我只是不知道这个过程叫什么。因此,由于方法重载只关心参数的类型和数量,我假设IntegerDouble 扩展Number 是无关紧要的?我可以使用任何旧课程吗?
    猜你喜欢
    • 2014-12-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多