Home  >  Q&A  >  body text

java实现继承时,为什么要重写父类方法而不是重新再写一个方法。

如题,最近看java基础时,看到了关于继承的重写和重载部分,方法的重载可以实现代码的多态,但是重写我就不是很理解为什么要这么写,希望有心人帮忙解释下。
小白这里先谢过了。

大家讲道理大家讲道理2764 days ago834

reply all(4)I'll reply

  • 阿神

    阿神2017-04-18 10:18:05

    If you rewrite, you can also achieve code diversity.

    After the subclass inherits the parent class, it does not need to rewrite the method of the parent class, which saves the amount of code.

    If the usage conditions change and the method of the parent class cannot meet the usage requirements, then you need to rewrite the method and overwrite the method of the parent class.

    Rewriting can work with many modes of Java.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:18:05

    You understand wrongly. Rewriting is the key to achieving polymorphism. Overloading just adds a few parameters and reuses method names. As for why rewriting is the key to achieving polymorphism, it is because object-oriented encourages interface-oriented programming, or abstraction-oriented programming. For example:

    The parent class of a fruit has a printName method:

    public class Fruit {
        public void printName() {
            System.out.println("Fruit");
        }
    }

    Both apples and oranges can be subclasses of Fruit, but you can override the printName method during implementation to achieve different name outputs.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:18:05

    One of the benefits of inheritance is to reduce the amount of code. There is no need to write the same statement in every class. Direct inheritance is like the relationship between a father and his son. The son will inherit all the characteristics of the father, but the son can also develop on his own.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:18:05

    Rewrite the parent class method and define a special class with a template. They all look the same on the outside, but they are different on the inside. This is the advantage of interface-oriented programming

    reply
    0
  • Cancelreply