kiran Biradar
kiran Biradar

Reputation: 12732

How to achieve Runtime polymorphism in 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

Upvotes: 4

Views: 557

Answers (3)

ItFreak
ItFreak

Reputation: 2369

When assigining Bike b = new Splender();, you assign the variable b a type of Bike. To access methods of Splender, you need to cast: ((Splender) b).run2();

As I saw your comment: implementing an interface results in the same compile "problem" that the compiler does not know about the 'specialized' methods, he will only know the interfaces methdods. But casting will work there too.
The only way to avoid this would be to move run2() to the interface which would be a contradiction to your question/use case

Upvotes: 4

Smutje
Smutje

Reputation: 18123

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.

Upvotes: 6

Murat Karagöz
Murat Karagöz

Reputation: 37584

By casting it again

((Splender)b).run2();

there is no other way.

Upvotes: 5

Related Questions