Java中什么是重载和重写(重载.重写.Java...)
当同一个类中的多个方法共享相同的名称但具有不同的参数(类型、数字或两者)时,就会发生方法重载。方法重载背后的主要思想是增加程序的可读性。
1.1 方法重载的特点- 相同的方法名称:所有重载的方法必须具有相同的名称。
- 不同的参数列表:方法的参数数量或类型必须不同。
- 编译时多态性:方法重载是 java 中编译时(或静态)多态性的一个示例。
让我们看一个简单的例子来说明方法重载:
public class calculator { // method to add two integers public int add(int a, int b) { return a + b; } // method to add three integers public int add(int a, int b, int c) { return a + b + c; } // method to add two doubles public double add(double a, double b) { return a + b; } }1.3 示例说明
在上面的示例中,calculator 类具有三个名为 add 的重载方法。每个方法都有不同的参数列表:
- 第一个方法需要两个 int 参数。
- 第二种方法需要三个int参数。
- 第三种方法需要两个double参数。
当调用 add 方法时,会根据传递的参数选择适当的版本。这使得代码更直观、更容易理解。
1.4 演示和结果public class testcalculator { public static void main(string[] args) { calculator calc = new calculator(); system.out.println("addition of two integers: " + calc.add(10, 20)); // outputs 30 system.out.println("addition of three integers: " + calc.add(10, 20, 30)); // outputs 60 system.out.println("addition of two doubles: " + calc.add(10.5, 20.5)); // outputs 31.0 } }2. java中的方法重写是什么?
当子类提供其超类中已定义的方法的特定实现时,就会发生方法重写。方法重写的目的是允许子类提供已由其超类之一定义的方法的特定实现。
2.1 方法重写的特点- 相同的方法签名:子类中的方法必须与超类中的方法具有相同的名称、返回类型和参数。
- 运行时多态性:方法重写是 java 中运行时(或动态)多态性的一个示例。
- @override 注释 :使用 @override 注释来指示某个方法正在重写超类方法是一个很好的做法。
让我们看一个方法重写的实际示例:
class animal { // method in the superclass void sound() { system.out.println("the animal makes a sound"); } } class dog extends animal { // overriding the sound() method in the subclass @override void sound() { system.out.println("the dog barks"); } }2.3 示例说明
在上面的例子中:
- animal 类有一个名为 sound 的方法,用于打印一般消息。
- dog 类扩展 animal 并重写 sound 方法以提供特定消息。
当在 dog 的实例上调用 sound 方法时,会执行 dog 中重写的方法。
2.4 演示和结果public class TestAnimal { public static void main(String[] args) { Animal myDog = new Dog(); // Upcasting myDog.sound(); // Outputs: The dog barks } }3. 重载与重写:主要区别 3.1 定义
- 重载 :涉及同一个类中具有相同名称但参数不同的多个方法。
- 重写:涉及在子类中重新定义已在超类中定义的方法。
- 重载 :代表编译时多态性。
- 重写:代表运行时多态性。
- 重载:方法绑定在编译时发生。
- 重写:方法绑定在运行时发生。
- 重载:当方法使用不同类型或数量的参数执行类似功能时使用。
- 重写:当子类需要为超类中已定义的方法提供特定实现时使用。
理解方法重载和方法重写之间的区别对于编写有效的 java 代码至关重要。重载允许多个方法具有相同名称但不同参数,从而增强代码的可读性和可用性。另一方面,重写使子类能够提供超类中已定义的方法的特定实现,从而促进运行时多态性。
如果您有任何疑问或需要进一步说明,请随时在下面发表评论。我是来帮忙的!
阅读更多帖子:java 中的重载和重写是什么
以上就是Java中什么是重载和重写的详细内容,更多请关注知识资源分享宝库其它相关文章!