Java 重载与重写

  1. 重载是在一个类里面,方法名字相同,而参数不同。返回类型可以相同也可以不同。每个重载的方法都必须有一个独一无二的参数类型列表。

  2. 重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变。

对重载函数的调用是在编译期就确定的,而对重写函数的调用是在运行期根据实际类型确定方法执行(动态性)

例如

class Shape {
}

class Circle extends Shape {
}

class Rectangle extends Shape {
}
public class Draw {

    public void draw(Shape shape) {
        System.out.println("Draw a shape");
    }

    public void draw(Circle circle) {
        System.out.println("Draw a circle");
    }

    public void draw(Rectangle rectangle) {
        System.out.println("Draw a rectangle");
    }

    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape rectangle = new Rectangle()

        Draw draw = new Draw();
        draw.draw(circle);
        draw.draw(rectangle);
    }
}
// 结果
// Draw a shape
// Draw a shape

因为是在编译期确定调用的函数,根据变量类型Shape,就都调用了参数类型为Shape的draw函数。

class Shape {
    public void draw() {
        System.out.println("Draw a shape");
    }
}

class Circle extends Shape {
    public void draw() {
        System.out.println("Draw a circle");
    }
}

class Rectangle extends Shape {
    public void draw() {
        System.out.println("Draw a rectangle");
    }
}
public class Draw2 {
    public void draw(Shape shape) {
        shape.draw();
    }
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape rectangle = new Rectangle();

        Draw2 draw = new Draw2();
        draw.draw(circle);
        draw.draw(rectangle);
    }
}
// 结果
// Draw a circle
// Draw a rectangle

重写的函数是在运行期根据实际类型确定执行的方法的,因此执行的是子类自己的draw函数,而不是父类的draw函数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值