在Java中,当有人问:

什么是多态性?

重载或重写是可以接受的答案吗?

我认为事情远不止如此。

如果你有一个抽象基类,它定义了一个没有实现的方法,并且你在子类中定义了这个方法,这仍然是覆盖的吗?

我认为超负荷肯定不是正确的答案。


当前回答

多态性就其意义而言更有可能……java中的override

这都是关于同一个对象在不同情况下的不同行为(在编程方式中…你可以调用不同的参数)

我认为下面的例子会帮助你理解……虽然它不是纯java代码…

     public void See(Friend)
     {
        System.out.println("Talk");
     }

但是如果我们改变参数…行为将会改变…

     public void See(Enemy)
     {
        System.out.println("Run");
     }

人(这里的“对象”)是一样的……

其他回答

重写和重载都用于实现多态性。

你可以在一个类中有一个方法 它在或中被覆盖 更多的子类。这个方法可以 不同的东西取决于哪个 类用于实例化对象。

    abstract class Beverage {
       boolean isAcceptableTemperature();
    }

    class Coffee extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature > 70;
       }
    }

    class Wine extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature < 10;
       }
    }

你也可以有一种方法 用两组或多组参数重载。这个方法可以 不同的东西基于 传递的参数类型。

    class Server {
        public void pour (Coffee liquid) {
            new Cup().fillToTopWith(liquid);
        }

        public void pour (Wine liquid) {
            new WineGlass().fillHalfwayWith(liquid);
        }

        public void pour (Lemonade liquid, boolean ice) {
            Glass glass = new Glass();
            if (ice) {
                glass.fillToTopWith(new Ice());
            }
            glass.fillToTopWith(liquid);
        }
    }

多态性简单来说就是“多种形式”。

它不需要继承来实现…作为接口实现,它根本不是继承,服务于多态需求。可以说,接口实现比继承更能满足多态需求。

例如,你会创建一个超类来描述所有会飞的东西吗?我不这么认为。你最好创建一个描述飞行的界面,然后就这样吧。

因此,由于接口描述行为,而方法名描述行为(对程序员来说),将方法重载视为一种较小形式的多态性并不过分。

术语重载指的是具有相同名称的东西的多个版本,通常是具有不同参数列表的方法

public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }

这些函数可能做同样的事情但你可以选择用ID或名称来调用它。与继承、抽象类等无关。

覆盖通常指的是多态性,就像你在问题中描述的那样

重写更像是通过声明一个与上层方法(超级方法)具有相同名称和签名的方法来隐藏一个继承的方法,这为类添加了多态行为。 换句话说,选择要调用的级别方法的决定将在运行时而不是在编译时做出。 这就引出了接口和实现的概念。

Polymorphism is a multiple implementations of an object or you could say multiple forms of an object. lets say you have class Animals as the abstract base class and it has a method called movement() which defines the way that the animal moves. Now in reality we have different kinds of animals and they move differently as well some of them with 2 legs, others with 4 and some with no legs, etc.. To define different movement() of each animal on earth, we need to apply polymorphism. However, you need to define more classes i.e. class Dogs Cats Fish etc. Then you need to extend those classes from the base class Animals and override its method movement() with a new movement functionality based on each animal you have. You can also use Interfaces to achieve that. The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods "with same name" but with different parameters on same object or class.