java方法与重载
方法与重载
方法
定义原则
- 一个方法最好只实现一个功能
- 方法中代码不宜过多,过多时应抽取为新的方法
- 定义时明确:返回值类型(有无结果)和形参列表(有无参与运算的数据)
语法
// 无返回值
public static void name() { }
// 有返回值
public static int name() {
return 值;
}
调用方式
public class TestMethod {
public static void main(String[] args) {
// 赋值调用
int sum = getSum();
// 输出语句调用
System.out.println(getSum());
// 直接调用
print();
}
public static int getSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void print() {
System.out.println("Hello!");
}
}
方法重载
条件
- 方法名称相同
- 参数列表不同(类型、个数、顺序不同,与参数名无关)
示例
public void read(String bookName, String bookAuthor) {
this.read(bookName, bookAuthor, 0.0);
}
public void read(String bookName, double bookPrice) {
this.read(bookName, null, bookPrice);
}
public void read(String bookName) {
this.read(bookName, null, 0.0);
}
public void read() {
this.read(null, null, 0.0);
}
内存演变
new Student() 过程
public class Student {
private String name = "";
{
this.name = "first";
}
public Student() {
this.name = "second";
}
}
执行顺序:name(null) → name("") → name("first") → name("second")
Scanner(控制台输入)
// 1. 引入 Scanner
import java.util.Scanner;
public class TestJava {
public static void main(String[] args) {
// 2. 创建对象
Scanner scan = new Scanner(System.in);
// 3. 读取输入
byte byteNum = scan.nextByte();
int intNum = scan.nextInt();
String str = scan.next(); // 读取字符串
scan.close();
}
}
注意:声明变量的类型要和 Scanner 方法返回的类型一致。