Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I have this 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

1 Answer

0 votes
by (13.1k points)

When assigning 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

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 6, 2021 in Java by Jake (7k points)

Browse Categories

...