重新定义方法和覆盖方法之间有什么区别? [英] What's the difference between redefining a method and overriding a method?

查看:156
本文介绍了重新定义方法和覆盖方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class DonkeyBattler {

    static void doBattle(){
        System.out.println("Weaponized donkey battling");
    }

}

class FunkyBattler extends DonkeyBattler {

    static void doBattle(){
        System.out.println("Weaponized donkey battling with bellbottoms");

    }
}

doBattle方法应该是一个重新定义或覆盖?哦顺便说一句,这就是Java。

doBattle method is supposed to be a redefinition or an override? Oh this is Java by the way.

推荐答案

术语重定义通常不用于Java方法和继承。通常使用两个术语:如你所说的覆盖和超载。在Java中重载是在同一个类中创建两个具有相同名称但签名不同的方法(参数的数量和/或类型)。例如:

The term "redefinition" isn't usually used with regards to Java methods and inheritance. There are two terms that are commonly used: "override" as you said, and "overload." To overload in Java is to create two methods in the same class with the same name but different signatures (number and/or types of arguments). For example:

public interface MyInterface
{
    public int doStuff(int first, int second);
    public int doStuff(double only);
}

要覆盖的是执行类似于您在示例中所做的事情:创建一个子类,其方法具有相同名称​​和签名作为父类中的方法,该方法将用于子类的所有实例,但不用于父类或任何其他子类的那个父母。

To override is to do something like what you are doing in your example: create a child class with a method that has the same name and signature as a method in the parent class that will be used for all instances of the child class but not of the parent class or any other child classes of that parent.

你的例子与重载有关的唯一问题是使用关键字 static 。覆盖是动态确定的,但根据定义静态方法不是。

The only issue with your example as it relates to overloading is the use of the keyword static. Overriding is determined dynamically, but static methods by definition are not.

这篇关于重新定义方法和覆盖方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆