大龄屌丝自学笔记--Java零基础到菜鸟--012

本文详细介绍了编程中的方法概念及其实现方式,并深入探讨了方法重载的特点与使用技巧。文章通过具体示例展示了如何定义和调用方法,以及如何利用重载实现同名方法的不同功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法,重载

 

1、方法:完成特定功能的代码块

格式:修饰符 返回值 方法名(参数类型 参数名1, ...... ,参数类型 参数名n){ 函数体; return 返回值; } 。

注意:“void” 方法不需要返回值,方法不能嵌套。

 1 class Fin{
 2 
 3     //main方法
 4     public static void main(String[] args){
 5         int n=test(3,2);        //调用test方法
 6         System.out.println(n);  //n=1  
 7     }
 8 
 9     //test方法
10     public static int test(int a,int b){
11          return a-b;
12     }
13 }

 

2、重载:同一个类中,允许同名不同参数(参数类型或参数个数不同)的方法

注意:与方法的返回值无关,只看方法名和参数(参数类型、参数个数),通过参数区分同名方法。

 1 class Fin{
 2     public static void main(String[] args){
 3         int n=test(3,2,1);
 4         System.out.println(n);  //n=6
 5     }
 6 
 7     public static int test(int a,int b){
 8         return a-b;
 9     }
10 
11     public static int test(int a,int b,int c){
12         return a+b+c;
13     }
14 }

转载于:https://www.cnblogs.com/liverpool/p/4761803.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值