I was asked today why you shouldn’t have your input (scanner and other methods for input) inside your class methods. The answer is simply versatility.
You want to be able to reuse as much of your Object Oriented code as possible. Generally that means abstracting your class. And abstracting means splitting things up.
Here’s a simple example.
If you have a Bank class and it has a method for adding to the balance, you would have the add method with a parameter that would simply be added to the class property balance. That’s how it should it work.
Keep your business logic separate from your presentation logic. Thusly, you’d get two classes, Banking and BankAccount. Banking is the class you have your main method in and it’s the class you interact with directly (and only). BankAccount is the class you have you balance variable and add/remove methods in.
The best way to show this in action is to make an entire mini-app to show everyone. (As much as I hate this blog’s code system, I’ll do it anyway.)
class BankAccount { public String name; private double balance; /* * Constructor. * * @param name The owner's name of this account. * @param value the initial value of this account. */ public BankAccount(String name, double value) { this.name = name; this.balance = value; } /* * Adds money to this bank account's balance. * * @param value the value to add to this account's balance. */ public void add(double value) { this.balance = this.balance + value; } /* * Withdraws money from this bank account's balance. * * @param value the value that will be withdrawan from this account's balance. */ public void withdraw(double value) { this.balance = this.balance - value; } /* * Gets the balance of this bank account. * * @return the balance of this account. */ public double getBalance() { return this.balance; } /* * Gets name of the owner of this bank account. * * @return the name of this account's owner. */ public String getAccountee() { return this.name; } }
Above is the BankAccount class, where you use it as only it. It will do nothing it dosen’t say. It’s only for bank accounts.
Additionally, you can download the full file with the class above. It’ll show you my presentation logic which is pretty fancy.