I am new to Java and got a doubt regarding Upcasting and Down-Casting. I have written the following code:
class Bike{
int speedlimit=90;
int bikeId = 123576;
Bike(){
System.out.println("inside Bike");} //end constructor
public void run(){ System.out.println("Bike is running");
}// end run
};//end Bike
class Honda3 extends Bike{
int speedlimit=150;
int bikeId = 456;
Honda3(){ System.out.println("inside Honda");} //end constructor
public void run(){ System.out.println("Honda is running");
}// end run
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);
System.out.println(obj.bikeId);
obj.run();
Honda3 obj2 = (Honda3) obj;
obj2.run();
obj.run();
} // end main
};//end honda3
Output:
inside Bike
inside Honda
90
123576
Honda is running
Honda is running
Honda is running
When I created Object obj It was upcast to Parent Class Bike, it shows or describes the variables declared inside the parent class and not in itself. But then it does not execute the run method inside the Parent Class i.e. Bike but it still executes the one in Honda3 class.
So my doubt is, whenever any object is upcast to its parent class does it lose all its properties or variables?
And also why can't an Upcast object cannot access parent method i.e. using the following?
`Bike obj = new Honda3(); // Output should be : Bike is Running`