您的位置:首页 > 编程语言 > Java开发

java方法中的参数和返回值的四种情况

2020-06-25 04:54 393 查看

方法中是否有参数和返回值分为四种情况:

1、无参无返

2、有参有返

3、有参无返

4、无参有返

代码实例:

Student类:

[code]package com.aaa.pac.classdemo;
public class Student {
//属性   ---成员变量
//姓名
String name;
//身高
float height;
//年龄
int age;
//性别
String sex;
//行为
void coding(){
System.out.println(name+"敲代码");
}
/**
* /** 回车 给方法进行注释
* 权限修饰符  返回值类型  方法名(参数列表--形式参数)
*      方法体
*  void 当前方法 不返回任何参数
*  play() 没有形参  不需要传递参数
* 无参无返
*/
void play(){
System.out.println(name+"玩耍");
System.out.println("这是play方法");
}
/**
*
* @param a
* @param b
* @return
* 有参有返
* add(int a,int b) 当调用当前方法时,必须传递对应参数一一对应,参数类型相同相同,个数相同
* int add(int a,int b) 返回值类型int 当前方法必须返回一个int类型的数据
*                      如果String或者其他类型 必须返回相应的类型 或者返回null
*/
int add(int a,int b){
System.out.println("a:"+a+"--b:"+b);
int result =a + b;
return result;
}
/**
* 设置年龄
* @param age
* 有参无返
*/
void setAge(int age){
//通过方法   设置年龄
//this.age代表获取当前对象的成员变量,当变量名和形参冲突时可以加以区别
this.age = age;
if (age > 15){
/*
* 1、无返回值方法,不需要返回值,写也不影响
* 2、return不在最后一行时,遇到return立即跳出整个方法。
*/
return;
}
System.out.println("形参age" + age);
System.out.println("成员变量--this.age" + this.age);
return;
}
/**
* 无参有返
* 使用场景:1、获取结果 2、之星对应业务 获取结果
* @return
*/
String getClassName(){
String className = null;
switch (age){
case 5:
className = "幼儿园-中班";
break;
case 6:
className = "幼儿园-大班";
break;
case 18:
className = "幼儿园-小班";
break;
default:
className = "其他";
break;
}
return className;
}
}

Test类:

[code]package com.aaa.pac.classdemo;
public class Test {
public static void main(String[] args) {
//创建一个对象
Student student = new Student();
//对某一个对象进行   成员变量初始化
student.name = "小明";
student.age = 18;
student.height = 180;
student.sex = "男";
//        //输出对象的属性
//        System.out.println("name" +student.name);
//        //调用对象的方法  变量名.方法名()
//        student.coding();
//调用无参无返方法
student.play();
//调用 有参 有返回值
//注意
int result = student.add(1,2);
System.out.println("result:"+result);
student.setAge(6);
System.out.println("studetnt:"+student.age);

//获取年级
String className = student.getClassName();
System.out.println("className:"+className);
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: