-
重载是在一个类里面,方法名字相同,而参数不同。返回类型可以相同也可以不同。每个重载的方法都必须有一个独一无二的参数类型列表。
-
重写是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变。
对重载函数的调用是在编译期就确定的,而对重写函数的调用是在运行期根据实际类型确定方法执行(动态性)
例如
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函数。