java实现继承时,为什么要重写父类方法而不是重新再写一个方法。
大家讲道理
大家讲道理 2017-04-18 10:16:05
0
4
846

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
阿神

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.

刘奇

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.

刘奇

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.

洪涛

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template