Reasons behind polymorphism related behaviour in java

Posted by Shades88 on Programmers See other posts from Programmers or by Shades88
Published on 2012-09-16T12:16:12Z Indexed on 2012/09/16 15:50 UTC
Read the original article Hit count: 191

Filed under:
|

I read this code somewhere

class Foo {
    public int a;
    public Foo() {
        a = 3;
    }
    public void addFive() {
        a += 5;
    }
    public int getA() {
        System.out.println("we are here in base class!");
        return  a;
    }
}

public class Polymorphism extends Foo{
   public int a;
   public Poylmorphism() {
       a = 5;
   }
   public void addFive() {
       System.out.println("we are here !" + a);
       a += 5;
   }

   public int getA() {
        System.out.println("we are here in sub class!");
        return  a;
    }

    public static void main(String [] main) {
        Foo f = new Polymorphism();
        f.addFive();
        System.out.println(f.getA()); // SOP 1
        System.out.println(f.a);      // SOP 2
    }
}

For SOP1 we get answer 10 and for SOP2 we get answer 3. Reason for this is that you can't override variables whereas you can do so for methods. This happens because type of the reference variable is checked when a variable is accessed and type of the object is checked when a method is accessed. But I am wondering, just why is it that way? Can anyone explain me what is the reason for this behaviour

© Programmers or respective owner

Related posts about java

Related posts about polymorphism