OOP实验3-类与对象

实验三 类与对象

实验三 类与对象
本实验4学时

  1. 实验目的:
    类与对象、成员变量、成员函数、构造函数

  2. 实验环境与条件:
    JDK, Netbeans

  3. 实验内容:
    编写一个类(class), 包括一些属性(代表数据的变量)和方法(代表功能的函数). 在main()函数中,根据这个类(class)创建一个对象. 调用这个对象的各种方法(成员函数).
    程序具体的功能/作用, 自己设定.

参考内容示例: 账户存取款.
附录: 类与对象的基本使用示例
文件 MainClass.java:

import java.util.Scanner;
public class MainClass {
    public static void main(String[] args) {
        String accountID = input("accountID");
        Account account = new Account(accountID, 0);
        account.deposit(100);
        output(account);
        String amountString = input("withdraw");
        int amount = Integer.parseInt(amountString);
        account.withdraw(amount);
        output(account);
    }
    public static String input(String prompt) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(prompt + ":");
        String result = scanner.next();
        return result;
    }
    public static void output(Account account) {
        System.out.println("Account " + account.getAccountID() + "'s balance is " + account.getBalance());
    }
}

文件Account.java:

public class Account {
    private String accountID;
    private int balance;
    public void deposit(int amount) {
        this.balance += amount;
    }
    public void withdraw(int amount) {
        this.balance -= amount;
    }
//以下代码是操作IDE自动生成的
    public Account() {
    }
    public Account(String accountID) {
        this.accountID = accountID;
    }
    public Account(String accountID, int balance) {
        this.accountID = accountID;
        this.balance = balance;
    }
    public int getBalance() {
        return balance;
    }
    public void setBalance(int balance) {
        this.balance = balance;
    }
    public String getAccountID() {
        return accountID;
    }
    public void setAccountID(String accountID) {
        this.accountID = accountID;
    }
}

你可能感兴趣的:(OOP)