Menu
CoddyTech

方法

本课属于 Coddy Java 学习旅程的“面向对象编程”单元。第 5 课,共 87 课。

方法定义了对象可以执行的操作。它们有返回类型、名称和可选参数。

没有参数的方法

public class Greeter {
    public String sayHello() {
        return "Hello!";
    }
}

带参数和返回类型的方法

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

无返回值的方法

public class Printer {
    public void printMessage(String msg) {
        System.out.println(msg);
    }
}

调用方法

Calculator calc = new Calculator();
int result = calc.add(5, 3);
System.out.println(result);  // 输出:8

返回类型会告诉 Java 方法返回哪种数据。方法执行操作但不返回数据时,使用 void。

challenge icon

挑战

中等

在 StringHelper 类中创建四个方法:

  • toUpperCase():返回大写形式的文本
  • getLength():返回文本的长度
  • contains(String word):如果文本包含该单词,则返回 true
  • repeat(int times):返回以空格分隔的重复文本

亲手试试

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        StringHelper helper = new StringHelper(input);
        
        System.out.println("Original: " + input);
        System.out.println("Uppercase: " + helper.toUpperCase());
        System.out.println("Length: " + helper.getLength());
        System.out.println("Contains 'World': " + helper.contains("World"));
        System.out.println("Repeated: " + helper.repeat(3));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Java 在线编译器