Reputation: 1061
Wasn't sure how to call my title, because I'm not sure how to call that problem right now.
I got one superclass
and three subclasses
. The subclasses
only got an own cunstructor
, all other methods and attributes are listed in the superclass
.
Now one of those three subclasses
have to contain a new attribute delay
and a method for that. But if I implement a somewhat generic
method (because it doesn't care which subclass is using it, because it checks it in the method itself.) but in the superclass in the method I want that if my object is of that specific subclass that it can access the delay.
Anyone can tell me how to achieve this without implementing the attribute into the superclass itself? (Only want that an object this subclass can access this delay attribute)
else if (this instanceof repairCar) {
if(this.getDelay() != 0){
}
}
Edit:
There is the superclass: Car
This contains methods like setSpeed and corresponding attributes
ant a method called drive.
now there are the subclasses: FastCar
NormalCar
RepairCar
which all only got a constructor in the subclass.
The RepairCar should have another attribute delay
due to it being repaired right now.
In the superclass in the drive method
it checks whether the Car is a FastCar
, NormalCar
or RepairCar
. When it is a RepairCar
it should check if the delay is 0 so It can drive otherwise it will wait a turn and lower the delay until its 0.
Now I want that only my RepairCar got this delay attribute and not my other two subclasses. But if my drive method is in the superclass it wont let me reference to the delay of a RepairCar due to the superclass not having this attribute.
Any way to implement the drive method for all 3 Cartypes in the Superclass without implementing the delay into the superclass?
Upvotes: 0
Views: 850
Reputation: 749
Why should the superclass be responsible for this? This should only be done by the specific class.
E.g.
public class Car {
public void drive() {
// do something all cars do
}
}
Your subclass is:
public class RepairCar extends Car {
public int delay() {
return this.delay;
}
@Override
public void drive() {
if (delay() == 0) {
super.drive();
} else {
decreaseDelay();
}
}
...
}
Upvotes: 1
Reputation: 2746
Couldn't you do something like:
abstract class AbstractCar {
public void performAction() {
// stuff
doSomething();
}
protected abstract void doSomething();
static class RepairCar extends AbstractCar {
private int delay;
@Override
protected void doSomething() {
// do something based on delay
}
}
static class FastCar extends AbstractCar {
@Override
protected void doSomething() {
// do something with no delay
}
}
}
Upvotes: 0