Reputation: 1482
I am very new to Java, and am working out a simple program showing inheritance. I am having issues accessing a method in a derived class, since it seems my variable definition does not use the subclass name, but the superclass name (Accounts). Why is it when I call the deposit method, a cannot find symbol error occurs?
import java.util.*;
import java.text.*;
public class Accounter {
static Scanner input = new Scanner(System.in);
static Accounts myAccount;
public static void main(String[] args) {
int result; //holder for user input
double amount; //holder for desposits and withdrawals
System.out.println("What kind of account would you like to setup?");
System.out.println("Checking[1] or Savings[2]");
result = input.nextInt();
if(result == 1) {
myAccount = new Checking();
} else {
myAccount = new Savings();
}
myAccount.deposit(199.99);
}
}
class Accounts {
double balance;
public String accountName;
public Date dateOpened;
public Date today = new Date();
public Accounts() {
dateOpened = today;
}
public Date getDateOpened() {
return dateOpened;
}
public double getBalance() {
return balance;
}
}
class Checking extends Accounts {
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}
class Savings extends Accounts {
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}
Upvotes: 1
Views: 401
Reputation: 107
myAccount
is an instance of Accounts
which is your base class.
You cannot access methods from the derived classes directly from a reference to the base class.
To call that method, you'd need to cast to the desired derived class:
if(result == 1) {
myAccount = new Checking();
} else {
myAccount = new Savings();
}
if(myAccount instanceof Checking)
(Checking)myAccount.deposit(199.99);
else if(myAccount instanceof Savings)
(Savings)myAccount.deposit(199.99);
...BUT...
Since your derived classes share the same method, it would be best to define that method in your base Accounts
class like so:
class Accounts {
...
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}
Then call your method as you did originally. This way you don't have to check whether myAccount
is instance of one derived class or another. And if you need to change the behavior of that method in a future derived class, you can override it.
Upvotes: 0
Reputation: 30146
Declare class Accounts
as abstract
.
Declare double balance
as a protected
field in this class.
Declare public void deposit(double amount)
as an abstract
method in this class.
Upvotes: 3
Reputation: 8836
deposit is not defined in your base class, what you should do is,
define this method in base class and override it in your sub classes.
public class Accounts{
public void deposit(double amount) {
}
}
class Checking extends Accounts {
@Override
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}
Upvotes: 1