当同一个类中的多个方法共享相同的名称但具有不同的参数(类型、数字或两者)时,就会发生方法重载。方法重载背后的主要思想是增加程序的可读性。
让我们看一个简单的例子来说明方法重载:
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; } }
在上面的示例中,calculator 类具有三个名为 add 的重载方法。每个方法都有不同的参数列表:
当调用 add 方法时,会根据传递的参数选择适当的版本。这使得代码更直观、更容易理解。
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 } }
当子类提供其超类中已定义的方法的特定实现时,就会发生方法重写。方法重写的目的是允许子类提供已由其超类之一定义的方法的特定实现。
立即学习“Java免费学习笔记(深入)”;
让我们看一个方法重写的实际示例:
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"); } }
在上面的例子中:
当在 dog 的实例上调用 sound 方法时,会执行 dog 中重写的方法。
public class TestAnimal { public static void main(String[] args) { Animal myDog = new Dog(); // Upcasting myDog.sound(); // Outputs: The dog barks } }
理解方法重载和方法重写之间的区别对于编写有效的 java 代码至关重要。重载允许多个方法具有相同名称但不同参数,从而增强代码的可读性和可用性。另一方面,重写使子类能够提供超类中已定义的方法的特定实现,从而促进运行时多态性。
如果您有任何疑问或需要进一步说明,请随时在下面发表评论。我是来帮忙的!
阅读更多帖子:java 中的重载和重写是什么
以上就是Java中什么是重载和重写的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号