-1

I have a BankAccount class which is superclass and SavingsAccount and CheckingAccounts as subclasses/derived classes. Very simple classes.

What is the difference between these first 3 lines of code vs next 3 lines of code.

First 3 lines of code"

 BankAccount b = new BankAccount(100);
 BankAccount s = new SavingsAccount(100);
 BankAccount c = new CheckingAccount(200);

Next 3 lines of code"

 BankAccount  b = new BankAccount(100);
 SavingsAccounts s= new SavingsAccount(100);
 CheckingAccount c = new CheckingAccount(200);
sid34
  • 17
  • 2

1 Answers1

1

There is no 'right' way. What do you want to do with these things? Are you interested in the fact that they're all accounts, or will you need to know what sort of account they are?

The general rule is "don't assume more than you need to". If the following code doesn't need to know that they have differences, declare the variables as BankAccount.

user15187356
  • 807
  • 3
  • 3
  • I am preparing for a test. And the question was about what methods can be accessed after the following lines of code. even though, In the right hand side of the = sign I am saying Savingsaccount and checkingaccount, it is only creating bankaccount objects. I don't understand. BankAccount b = new BankAccount(100); BankAccount s = new SavingsAccount(100); BankAccount c = new CheckingAccount(200); – sid34 Mar 08 '21 at 19:43
  • I think that the link about "programming to an interface" (given above) is the most relevant. Leaving your code aside, you'll often see `List myList = new ArrayList<>()`. Why is it written that way? First of all, the subsequent code will work with any sort of List at all, so it would be overly restrictive to insist it be given specifically an ArrayList. But on the other hand, the programmer figured that ArrayList was a good choice for the implementation (it's fairly compact, efficient enough unless you want a lot of deletions from the middle, or a few other concerns). – user15187356 Mar 08 '21 at 23:45