-1

I am studying run time polymorphism, I find one example like this

class Bike {
    void run() {
        System.out.println("running");
    }
}

class Splender extends Bike {
    void run(){
        System.out.println("running safely with 60km");
    }

   public static void main(String args[]){
       Bike b = new Splender (); //upcasting
       b.run();
   }
}

here Bike class object b can access method run of Splender its okay, so can we access run() method of Bike? if yes then how? if not then why?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
dev_swat
  • 1,264
  • 1
  • 12
  • 26

1 Answers1

0

No, it was overridden by Splender. You use an instance of Splender, so its version of the method is going to be used.

You have access to it while overriding it, though.

@Override
void run() {
    super.run();
    System.out.println("running safely with 60km");
}

8.4.8.1. Overriding (by Instance Methods)

An overridden method can be accessed by using a method invocation expression (§15.12) that contains the keyword super. A qualified name or a cast to a superclass type is not effective in attempting to access an overridden method.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • b is object of Bike, then why its not accessing Bike method? – dev_swat Sep 12 '19 at 10:17
  • 1
    @dev_swat the actual (or run-time) type of `b` is `Splender` which overrides the method. The declared type of a variable doesn't matter when it comes to method overriding – Andrew Tobilko Sep 12 '19 at 10:22
  • "You have access to it while overriding it, though." - just to clarify this a bit: "You have access to [the function] while overriding [the class], though". – Quaffel Sep 12 '19 at 10:30
  • @Quaffel I am not overriding the class, though – Andrew Tobilko Sep 12 '19 at 18:51
  • In the example above, you did. There's nothing wrong with it. However, I just wanted to clarify that calling the parent's implementation of `#run()` isn't limited to the scope inside the overridden function. The formulation "overriding the class" might have been a little missleading since it doesn't refer to "overriding" in the classical sense. – Quaffel Sep 12 '19 at 18:57