Consider the below program:
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){
System.out.println("running safely with 60km");
}
void run2(){
System.out.println("running2 safely with 60km");
}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run2();
}
}
My Question:
b.run2();
How to access the run2
method of derived class using base class object?
As of now it is throwing compilation error:
242/Splender.java:12: error: cannot find symbol
b.run2();
^
symbol: method run2()
location: variable b of type Bike
1 error
To be able to access methods declared in subclasses, one has to downcast to the respective class:
((Splender) b).run2();
Which of course might result in a runtime error when using an incompatible object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With