简体   繁体   中英

Method for getting value for primitive types

II am having so much trouble getting this method: A method in SmallBank named printBankDetailsthat prints out the details of the stored BankAccounts. This method should work in the case that there is only one BankAccount as well as in the case that there are two BankAccounts. You can check whether there is a value in the account2 instance variable as follows. I have no idea how to get the value of the primitive types I created, account1 and account2 then print that value. Any suggestions?

public class SmallBank
{
    private BankAccount account1;
    private BankAccount account2;

    public SmallBank(String name, int balance)
    {
        account1 = new BankAccount(name, balance);
        account2 = null;
    }

    public void addSecondAccount(BankAccount newAccount)
    {
        account2 = newAccount;
    }

    public void printBlankDetails()
    {
        account1.getDeclaredFields();
        String name = field.getName();
        Int balance = field.getBalance();
        System.out.println(b);

    }
}

First of all, account1 and account2 are NOT primitive types.

Also, you can access both quite simply as below.

public void printBlankDetails()
{
    String name1 =  account1.getName();


    String name2 =  account2.getName();

}

ps there are many issues with your printBlankDetails function, so I didnt attempt to replicate it.

You could declare BankAccount as:

class BankAccount {

    private int balance;
    private String name;

    public BankAccount (String name, int balance) {
        this.name = name;
        this.balance = balance;
    }

    public String getName () {
        return name;
    }

    public int getBalance () {
        return balance;
    }

}

Then you call the methods in SmallBank class:

public void printBankDetails () {
    System.out.println("Account 1:");
    System.out.println("Name: " + account1.getName());
    System.out.println("Balance: " + account1.getBalance());
}

An alternate design is to have say printDetails() in the BankAccount class itself. Something like:

public class BankAccount {
  String name;
  int balance;
  ...
  ...

  public String printDetails() {
      return (name + "/" + balance);
  }
}

and then use it in your SmallBank::printBlankDetails() method as follows:

printBlankDetails() {
   if(account1 != null) system.out.println(account1.printDetails());
   if(account2 != null) system.out.println(account2.printDetails());
}

IMO, this approach provides better encapsulation, hides the details of BankAccount from SmallBank class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM