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

本文介绍了Java中的方法重载(Overload)和重写(Override)概念。重载涉及在同一个类中拥有同名但参数不同的多个方法,而重写则是在父类和子类间,具有相同参数但实现不同的方法。Java中的构造函数是重载的一个常见示例。
摘要由CSDN通过智能技术生成

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中的构造函数是函数重载的一种表现,重载对于构造函数是强制性的。这种重载方式带来的方便也可以用于任何其他的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值