0
class one {

    public void print_geek(){
        System.out.println("Geeks");
    }
}
class two extends one {

    public void print_for() { 
        System.out.println("for"); 
    }
}
public class Main {

    public static void main(String[] args){
        two g = new two();
        one h = g;
        g.print_geek();
        h.print_for();
        g.print_geek();
    }
}

While trying to run the above code I am getting error:

"error: cannot find symbol
        h.print_for();
         ^
  symbol:   method print_for()
  location: variable h of type one "

Despite h and g being same object. I having hard time understanding what is the issue here?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Rohit
  • 1
  • 1
  • Same object but not the same variable. The Java compiler sees that `h` is `one` type and thus only has methods of `one` available to it (unless it is cast). This gets down to the basic difference between variables and objects. This also makes sense since you can re-assign `h` later to be a `one` instance. – Hovercraft Full Of Eels Jun 27 '21 at 11:53
  • Please also look at this Q&A: [Calling method from java child class not in parent class](https://stackoverflow.com/questions/42562916/calling-method-from-java-child-class-not-in-parent-class) – Hovercraft Full Of Eels Jun 27 '21 at 11:57
  • but this works if i change the name of method of class one from print_geek to print_for(). And then when i run the code it displays the statment of print_for() from class two i.e "for" – Rohit Jun 27 '21 at 11:57
  • Exactly -- and you should be able to figure out why this is so – Hovercraft Full Of Eels Jun 27 '21 at 11:58
  • This is due to polymorphism, the h object for the g but casted as an object of the one class, if you want to get the original g, I think you should call it this way (Two)g and call the method – WhiteReve Jun 27 '21 at 13:01
  • @WhiteReve as is well-discussed in the 2nd duplicate Q&A – Hovercraft Full Of Eels Jun 27 '21 at 13:02

0 Answers0