So I am having some confusion understanding dynamic binding vs upcasting.
My original understanding was that when you create a base_class
reference and assign it to a derived class object like:
base_class obj = new derived_class();
you can now call the methods/member functions of derived_class
with obj.method_of_derived class()
, without dynamic binding.
I thought you only needed dynamic binding when the base_class
and derived_class
have functions/methods that have the same name, and some sort of overriding needs to happen during the compile time to assign them correctly.
Am I totally wrong?
or is there another reason the below code doesn't work?
public class Ticket {
protected String flightNo;
public Ticket(){
this.flightNo = new String();
}
public void setTicket(lnode ticket){
this.flightNo= ticket.getFlightNumber();
}
public void displayTicket(){
System.out.println("Flight number: " + this.flightNo);
}
}
And a derived class extended from the above class
public class originalTicket extends Ticket {
protected boolean catchAnotherFlight;
protected boolean baggageTransfer;
public originalTicket(){
catchAnotherFlight = false;
baggageTransfer = false;
}
public void setoriginalTicket(lnode ticket){
setTicket(ticket);
}
}
and I am unable to do this:
Ticket object = new originalTicket();
object.setoriginalTicket();//Can't call the originalTicket method.
I have written some programs using upcasting in C++ but I always used dynamic binding. I was just trying to pick up Java and now I am a little startled that I got all the concepts wrong all along. Thanks.