Thinking in java-17 重载和重写Overload & Override

来源:互联网 发布:js窗口高度 编辑:程序博客网 时间:2024/06/10 11:00

1. Overload && Override

这里有相关的stackflow链接。
Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {    void foo(double d) {        // do something    }}class Child extends Parent {    @Override    void foo(double d){        // this method is overridden.      }}

方法重载:在同一个类中,函数名相同,但是函数参数不同的情况。
函数重载的条件:函数的参数个数、函数参数的类型、函数参数的顺序之一不同即可构成重载;但是函数的返回值不同并不能构成重载。
方法重写:函数重写override意味着函数有相同的参数,却有不同的实现。重写的方法其中之一在父类中存在,另一个在子类中被重写。

2. 实例

package fqy.iss.thinking.Control;public class Range{    public static int[] range(int n)    {        int[] result = new int[n];        for (int i = 0; i < n; i++)            result[i] = i;        return result;    }    public static int[] range(int start, int end)    {        int size = end - start;        int[] result = new int[size];        for (int i = 0; i < size; i++)            result[i] = start + i;        return result;    }    public static int[] range(int start, int end, int step)    {        int size = (end - start) / step;        int[] result = new int[size];        for (int i = 0; i < size; i++)            result[i] = start + i * step;        return result;    }}
class A{    public void say(){        System.out.println("In parent class.");        }    }class B{    @Override    public void say(){        System.out.println("In derived class.");        }    }

Java中的构造函数是函数重载的一种表现,重载对于构造函数是强制性的。这种重载方式带来的方便也可以用于任何其他的方法。