在Java中,重载(overloading)和重写(overriding)是两个不同的概念,它们的应用场景也不同。
重载是指在同一个类中定义了多个方法,它们的方法名相同但参数列表不同。重载的目的是方便程序员,使得程序代码更加简洁,更易读懂。
重写是指子类重写了父类的方法,方法名和参数列表都相同。重写的目的是为了改变父类方法的行为,实现多态性。
下面是一些示例代码:
重载的例子:
public class OverloadExample { public void print(int i) { System.out.println("Integer: " + i); } public void print(double d) { System.out.println("Double: " + d); } public void print(String s) { System.out.println("String: " + s); }}// 在其他类中使用 OverloadExample 中的方法OverloadExample oe = new OverloadExample();oe.print(1);oe.print(2.0);oe.print("hello");
上述代码中,OverloadExample 类中定义了三个方法,分别使用了不同的参数类型。在其他类中,可以通过对象oe调用这些方法,Java会根据传入的参数类型选择合适的方法进行调用。
重写的例子:
public class Animal { public void speak() { System.out.println("I am an animal"); }}public class Cat extends Animal { @Override public void speak() { System.out.println("I am a cat"); }}// 在其他类中使用 Cat 中的方法Animal animal = new Cat();animal.speak();
上述代码中,Animal类中定义了一个speak方法,Cat类继承了Animal类并重写了speak方法。在其他类中,可以创建一个Cat对象,并将其赋值给Animal类型的变量animal。调用animal的speak方法时,实际上调用的是 Cat类中重写的speak方法。这就体现了多态性的特点。
Copyright © 2013-2021 河南云和数据信息技术有限公司 豫ICP备14003305号 ISP经营许可证:豫B-20160281