类和对象及类与类的使用经典题目—关卡4

类和对象的定义及使用

1.定义

 

 

2 .了解关键字private,this的使用和作用

private——保护成员不被别的类使用,只有在private修饰的成员能使用

提供get变量名()方法,用于获取成员变量的值,方法用public修饰

提供set变量名(参数)方法,用于设置成员变量的值,方法用public修饰

this——his修饰的变量用于指代成员变量

方法的形参如果与成员变量同名,不带this 修饰的变量指的是形参,而不是成员变量
方法的形参没有与成员变量同名,不带 this 修饰的变量指的是成员变量

3.类与类的经典例题(个人错题)

①.写一个名为Account的类模拟账户。该类的属性和方法如下图所示。该类包括的属性:账号id,余额balance,年利率annualInterestRate;包含的方法:访问器方法(getter和setter方法),取款方法withdraw(),存款方法deposit()。

②.创建Customer类。

③.写一个测试程序。

(1)创建一个Customer ,名字叫 Jane Smith, 他有一个账号为1000,余额为2000元,年利率为 1.23% 的账户。

(2)对Jane Smith操作。

存入 100 元,再取出960元。再取出2000元。

打印出Jane Smith 的基本信息


效果如图:

成功存入 :100.0

成功取出:960.0

余额不足,取款失败

        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }



    public void   deposit(double inmoney){

          this.  balance +=inmoney;
        System.out.println("存入"+inmoney+"总余额"+balance);
        }

    public void withdraw(double outmoney){
        if(this.balance<outmoney){
            System.out.println("取款失败,余额不足");
            return;
        }else{
            this.balance-=outmoney;
            System.out.println("取出"+outmoney+"/t"+"当前账户余额为"+balance);
        }
    }
}
public class DEmo1 {
    private String firstName;
    private String lastName;

    private DEmo demo;

    public DEmo1(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    //把账户的类与客户建立联系
    public DEmo getDemo() {
        return demo;
    }

    public void setDemo(DEmo demo) {
        this.demo = demo;
    }

}
public class DEmo2 {
    public static void main(String[] args) {
            DEmo1 customer=new DEmo1("SNAKE","AAA");
            DEmo account=new DEmo(5134,1000,0.1234);
            customer.setDemo(account);//把账户给顾客使用
            customer.getDemo().deposit(1000);//具体账户的方法
            customer.getDemo().withdraw(900);
            customer.getDemo().withdraw(1500);
        System.out.println(customer.getFirstName()+customer.getLastName()+"他有一个id****账户余额为"+account.getId()+"**"+account.getBalance());
    }

}

注:在类与类的使用中,注意set,get构参的使用,在调用第二个类时,把它看一个整体,在用它的具体属性,具体方法

猜你喜欢

转载自blog.csdn.net/m0_59619191/article/details/119273023
今日推荐