Java什么时候该加void_平时容易忽视的地方之一:java在抽取方法时,什么时候该用void...
當一個類中多個方法有相同編碼,或該部分編碼可以作為一個整體,適合抽取出一個方法時,要注意這個抽取的方法的返回值,什么時候可以用void,什么時候不能用void?
先看代碼:
import lombok.Data;
import org.junit.Test;
public class MyTest {
@Test
public void test(){
Student student = new Student();
student.setName("Jacky");
int age = 18;
Double score = 80.0;
this.setValue(student, age, score);
System.out.println("age = " + age);
System.out.println("score = " + score);
System.out.println(student);
}
private void setValue(Student student, int age, Double score){
age += 1;
score += 10.0;
student.setAge(age);
student.setScore(score);
}
@Data
class Student{
String name;
int age;
Double score;
}
}
運行結果:
age = 18
score = 80.0
MyTest.Student(name=Jacky, age=19, score=90.0)
上面例子說明,當抽取方法參數是普通類時,方法返回值適合用void,相當于“把該類在一個地方過了一遍”;當抽取方法的參數是基本類型或包裝類型時,該方法應該有返回值。
總結
以上是生活随笔為你收集整理的Java什么时候该加void_平时容易忽视的地方之一:java在抽取方法时,什么时候该用void...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在java中jvm目录_JVM具体在哪个
- 下一篇: 转专业计算机c语言,转专业申请美国计算机