Java 实例 - 方法重载

Java 教程 · 2019-02-10 14:57:25

先来看下方法重载(Overloading)的定义:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。 具体说明如下:

  • 方法名相同
  • 方法的参数类型,参数个不一样
  • 方法的返回类型可以不相同
  • 方法的修饰符可以不相同
  • main 方法也可以被重载

以下实例演示了如何重载 MyClass 类的 info 方法:

MainClass.java 文件

class MyClass { int height; MyClass() { System.out.println("无参数构造函数"); height = 4; } MyClass(int i) { System.out.println("房子高度为 " + i + ""); height = i; } void info() { System.out.println("房子高度为 " + height + ""); } void info(String s) { System.out.println(s + ": 房子高度为 " + height + ""); } } public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(3); t.info(); t.info("重载方法"); //重载构造函数 new MyClass(); } }

以上代码运行输出结果为:

房子高度为 3 米
房子高度为 3 米
重载方法: 房子高度为 3 米
无参数构造函数

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

Introduction to Computation and Programming Using Python

Introduction to Computation and Programming Using Python

John V. Guttag / The MIT Press / 2013-7 / USD 25.00

This book introduces students with little or no prior programming experience to the art of computational problem solving using Python and various Python libraries, including PyLab. It provides student......一起来看看 《Introduction to Computation and Programming Using Python》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器