I have an abstract class Flight. Flight contains the method schedule() which calls the private method schedule(final Flight f)
public void schedule()
{
schedule(this);
}
private void schedule(final Flight f)
{
new Timer().schedule(new TimerTask()
{
@Override
public void run()
{
f.checkIn();
updateList();
}
}, this.getDate());
}
Lets now say I have a class SouthWestFlight that extends Flight
Flight f = new SouthWestFlight(); //ignore the missing params doesn't matter for example
f.schedule();
Would this pass the instance of the Flight or the instance of SouthWestFlight as a parameter in the schedule method?
Would this pass the instance of the Flight or the instance of SouthWestFlight as a parameter in the schedule method?
The instance of Flight
it's exactly the instance of SouthWestFlight
. You don't have 2 different instances. Your SoutWestFlight instance IS A Flight. Actually you can't have a Flight
instance itself cause it's abstract.
The instance of Flight
and SouthhWestFlight
are actually the same instance. There is only one instance to pass, and it will be passed.
I've prepared a simple test app.
public class TEST {
static abstract class Flight {
String type = "Flight";
abstract String getDirection();
public String getType() {
return this.type;
}
public void schedule() {
System.out.printf("Scheduled a %s towards %s",this.getType(),this.getDirection());
System.out.println();
System.out.printf("ReadyToGo: %s",this.isReadyToGo());
}
public boolean isReadyToGo() {
return false;
}
}
static class SouthWestFlight extends Flight {
String type = "SouthWestFlight";
@Override
String getDirection() {
return "SouthWest";
}
@Override
public boolean isReadyToGo() {
return true;
}
}
public static void main(String... args) {
new SouthWestFlight().schedule();
}
}
Output:
Scheduled a Flight towards SouthWest
ReadyToGo: true
Conclusions
Here the SouthWestFlight
object is still a Flight
Object.
But when you extend a class the child class overrides all the methods of parent class.
That is why isReadyToGo()
of SouthWestFlight() returned true.
None of the properties are overriden.
That is why this.getType()
returns Flight
.
But if you override the getType()
method with a new method in SouthWestFlight
like this:
@Override
public String getType() {
return this.type;
}
It will return type
field of SouthWestFlight
. Wondering why?
It is because, the first getType()
method is defined in parent class Flight
. So it returns type
field of class Flight
. The second getType()
method is defined in SouthWestFlight
so it returns type
field of SouthWestFlight
.
Hope you've got it clear. Please comment if you found any mistake or got any doubt.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.