Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve Runtime polymorphism in java

Tags:

java

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
like image 865
kiran Biradar Avatar asked Dec 05 '22 09:12

kiran Biradar


1 Answers

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.

like image 142
Smutje Avatar answered Dec 21 '22 13:12

Smutje