Java成员方法案例如何编写

wen java案例 29

本文目录导读:

Java成员方法案例如何编写

  1. 基础成员方法案例
  2. 方法重载案例
  3. 方法递归案例
  4. 静态方法案例
  5. 综合案例:银行账户系统
  6. 方法设计最佳实践

我来为你详细介绍Java成员方法的编写案例,从基础到进阶。

基础成员方法案例

学生类示例

public class Student {
    // 成员变量
    private String name;
    private int age;
    private double score;
    // 构造方法
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // 成员方法 - Getter和Setter
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            System.out.println("年龄不合法");
        }
    }
    // 成员方法 - 业务逻辑方法
    public void study() {
        System.out.println(name + "正在学习");
    }
    // 带参数的方法
    public void study(String subject) {
        System.out.println(name + "正在学习" + subject);
    }
    // 带返回值的方法
    public double getGradeLevel() {
        if (score >= 90) return 'A';
        else if (score >= 80) return 'B';
        else if (score >= 70) return 'C';
        else if (score >= 60) return 'D';
        else return 'F';
    }
    // 显示学生信息的方法
    public void displayInfo() {
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
        System.out.println("成绩:" + score);
        System.out.println("等级:" + getGradeLevel());
    }
}

方法重载案例

public class Calculator {
    // 方法重载:计算两个整数之和
    public int add(int a, int b) {
        return a + b;
    }
    // 方法重载:计算三个整数之和
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    // 方法重载:计算两个浮点数之和
    public double add(double a, double b) {
        return a + b;
    }
    // 方法重载:字符串拼接
    public String add(String a, String b) {
        return a + b;
    }
    // 方法重载:数组求和
    public int add(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return sum;
    }
}
// 测试类
public class CalculatorTest {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 3));           // 输出:8
        System.out.println(calc.add(5, 3, 2));        // 输出:10
        System.out.println(calc.add(3.5, 2.5));       // 输出:6.0
        System.out.println(calc.add("Hello", " World")); // 输出:Hello World
        System.out.println(calc.add(new int[]{1,2,3,4,5})); // 输出:15
    }
}

方法递归案例

public class RecursionExample {
    // 递归方法:计算阶乘
    public int factorial(int n) {
        // 基线条件
        if (n <= 1) {
            return 1;
        }
        // 递归调用
        return n * factorial(n - 1);
    }
    // 递归方法:斐波那契数列
    public int fibonacci(int n) {
        if (n <= 1) {
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    // 递归方法:数组求和
    public int sumArray(int[] arr, int index) {
        if (index >= arr.length) {
            return 0;
        }
        return arr[index] + sumArray(arr, index + 1);
    }
    // 测试递归
    public static void main(String[] args) {
        RecursionExample rec = new RecursionExample();
        System.out.println("5! = " + rec.factorial(5));      // 输出:120
        System.out.println("第8个斐波那契数:" + rec.fibonacci(8)); // 输出:21
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("数组和为:" + rec.sumArray(arr, 0)); // 输出:15
    }
}

静态方法案例

public class MathUtils {
    // 静态变量
    public static final double PI = 3.14159;
    private static int instanceCount = 0;
    // 构造方法
    public MathUtils() {
        instanceCount++;
    }
    // 静态方法:计算圆的面积
    public static double calculateCircleArea(double radius) {
        return PI * radius * radius;
    }
    // 静态方法:获取实例数量
    public static int getInstanceCount() {
        return instanceCount;
    }
    // 静态方法:判断是否为质数
    public static boolean isPrime(int number) {
        if (number <= 1) return false;
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) return false;
        }
        return true;
    }
    // 静态方法:最大值
    public static int max(int a, int b) {
        return a > b ? a : b;
    }
}
// 测试静态方法
public class MathUtilsTest {
    public static void main(String[] args) {
        // 无需创建实例,直接通过类名调用静态方法
        double area = MathUtils.calculateCircleArea(5);
        System.out.println("半径为5的圆面积:" + area);
        System.out.println("17是质数吗?" + MathUtils.isPrime(17));
        // 创建实例测试计数器
        new MathUtils();
        new MathUtils();
        System.out.println("实例数量:" + MathUtils.getInstanceCount()); // 输出:2
    }
}

综合案例:银行账户系统

public class BankAccount {
    // 成员变量
    private String accountNumber;
    private String accountName;
    private double balance;
    private static double interestRate = 0.03; // 静态变量:利率
    // 构造方法
    public BankAccount(String accountNumber, String accountName) {
        this.accountNumber = accountNumber;
        this.accountName = accountName;
        this.balance = 0;
    }
    // 带余额的构造方法
    public BankAccount(String accountNumber, String accountName, double initialBalance) {
        this(accountNumber, accountName);
        if (initialBalance > 0) {
            this.balance = initialBalance;
        }
    }
    // 存款方法
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存款成功,当前余额:" + balance);
        } else {
            System.out.println("存款金额必须大于0");
        }
    }
    // 取款方法
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取款成功,当前余额:" + balance);
            return true;
        } else if (amount > balance) {
            System.out.println("余额不足");
            return false;
        } else {
            System.out.println("取款金额必须大于0");
            return false;
        }
    }
    // 转账方法
    public boolean transfer(BankAccount target, double amount) {
        if (this.withdraw(amount)) {
            target.deposit(amount);
            System.out.println("转账成功");
            return true;
        }
        System.out.println("转账失败");
        return false;
    }
    // 计算利息方法
    public double calculateInterest() {
        return balance * interestRate;
    }
    // 静态方法:修改利率
    public static void setInterestRate(double rate) {
        if (rate >= 0 && rate <= 1) {
            interestRate = rate;
        } else {
            System.out.println("利率必须在0-1之间");
        }
    }
    // 显示账户信息方法
    public void displayAccountInfo() {
        System.out.println("========== 账户信息 ==========");
        System.out.println("账号:" + accountNumber);
        System.out.println("户名:" + accountName);
        System.out.println("余额:" + balance);
        System.out.println("年利率:" + (interestRate * 100) + "%");
        System.out.println("预期年利息:" + calculateInterest());
        System.out.println("==============================");
    }
    // Getter方法
    public String getAccountNumber() {
        return accountNumber;
    }
    public double getBalance() {
        return balance;
    }
}
// 测试类
public class BankSystem {
    public static void main(String[] args) {
        // 创建账户
        BankAccount account1 = new BankAccount("1001", "张三", 10000);
        BankAccount account2 = new BankAccount("1002", "李四");
        // 显示初始信息
        account1.displayAccountInfo();
        account2.displayAccountInfo();
        // 进行交易
        account1.deposit(5000);
        account1.withdraw(2000);
        // 转账
        account1.transfer(account2, 3000);
        // 修改利率
        BankAccount.setInterestRate(0.035);
        // 显示更新后的信息
        account1.displayAccountInfo();
        account2.displayAccountInfo();
        // 计算总资产
        double totalAssets = account1.getBalance() + account2.getBalance();
        System.out.println("两个账户总余额:" + totalAssets);
    }
}

方法设计最佳实践

方法命名规范

  • 使用动词开头:getXxx(), setXxx(), calculate(), display()
  • 语义清晰,见名知意

方法参数设计

// 好的设计:方法参数数量合理
public void createUser(String name, int age) {
    // 实现代码
}
// 避免过多的参数,可以使用对象封装
public void createUser(UserInfo userInfo) {
    // 实现代码
}

方法返回值设计

// 明确的返回值
public boolean isAdult(int age) {
    return age >= 18;
}
// 返回可选值,避免返回null
public Optional<String> findUserName(int userId) {
    // 如果找到返回Optional.of(name)
    // 如果没找到返回Optional.empty()
}

异常处理

public void divide(int a, int b) {
    try {
        if (b == 0) {
            throw new IllegalArgumentException("除数不能为0");
        }
        int result = a / b;
        System.out.println("结果:" + result);
    } catch (IllegalArgumentException e) {
        System.out.println("错误:" + e.getMessage());
    }
}

这些案例覆盖了Java成员方法的主要使用场景,从基础到进阶,从简单到复杂,建议你按照这些示例动手编写和测试,加深对成员方法的理解。

抱歉,评论功能暂时关闭!