Java入门第四课:类的封装

package mp;

import java.text.DecimalFormat;

class Account {
        private double amount;

        public Account() {
        }

        public Account(double balance) {
                setAmount(balance);
        }

        public double getAmount() {
                return amount;
        }

        public void setAmount(double amount) {
                if (amount > 0)
                        this.amount = amount;
                else
                        this.amount =0;
        }

        public String toString() {
                DecimalFormat df = new DecimalFormat("#,###.0000");
                return df.format(amount);
        }
}

public class Exec {
        public static void main(String[] args) {
                Account acc1 = new Account(100);
                acc1.setAmount(111);
                System.out.println(acc1);
        }
}

发表评论

邮箱地址不会被公开。 必填项已用*标注