Reputation: 917
I'm new to creating subclasses and do not know how I can "restrain" the functionality of the subclass although I'm using the superclasses' functionality.
In my subclass, I want to use the getCash()
method in my superclass, but I only want it to give me a result, if there has been more than 5 days since the date
stored in my subclass. My code looks like this:
public class Super{
private double cash;
public Super(double cash){
this.cash = cash;
}
public void deposit(double amount) {
if (amount > 0){
this.cash += amount;
}
}
public double getCash(){
if (this.cash > 0){
return this.cash;
}else {
return 0;
}
}
}
public class Sub extends Super {
private LocalDate date;
public Sub(double cash) {
super(cash);
}
}
Is this the right way of attacking the problem? Or should I implement all the logic needed in my superclass, and just pass a variable telling it wether it's the superclass or the subclass calling the function? What is the best practice?
Thank you in advance.
Upvotes: 1
Views: 94
Reputation: 817
You can use polymorphism to redefine functions in a subclass.
The function needs to have the same same signature (name + parameters).
public class Sub extends Super {
private LocalDate date;
public Sub(double cash) {
super(cash);
}
public double getCash() {
if (/* your date check */) {
return super.getCash();
}
return 0.0;
}
}
Thanks to shikjohari.
See : JAVA Polymorphism
Upvotes: 1
Reputation: 2288
The behaviour of returning only when the date difference is of 5 days is your subclass's behaviour so you have to write that condition in subclass only, However after the condition check you can call the super.getCash()
I think you can use the method in your subclass as
public double getCash() {
if (/* your date check 8*/) {
return super.getCash();
}
return 0.0;
}
Upvotes: 1