Tuesday, May 8, 2012

Confusion about superclass references and subclass objects

I have some questions about this code:



class superclass
{
p.bark()
}

class subclass extends superclass
{
p.bark
}

{
p.s.v.m()
superclass refvar = new subclass();
p.bark();
}



  1. Why is it necessary for the parent to have a method in this case, whether the child has it or not? I am told that at compile time the reference variable is of superclass type, so the compiler checks for this method in the superclass at compile time; is that accurate?


  2. When the compiler reads p.bark(), how does it know where to go next? I know the child method overrides it, but I want to know that first it goes to the superclass method or subclass, and why.


  3. Why does the subclass need to have an access modifier of wider scope?






No comments:

Post a Comment