2

I've been struggle to understand something that I'm sure is very simple, yet I'm newbie in java so I'm asking you guys:

public class A
{

    public int num;

    /**
     * Constructor for objects of class A
     */
    public A(){
        num = 222;
    }
    public A(int n){
        num = n;
    }

    public int getNum(){
        return num;
    }
    public boolean f(A a){
        return num == a.num*2;
    }
}



public class B extends A
{

    public int num;


    public B(int n)
    {
        num = n;
    }

    public boolean f(B b){
        return num == b.num;
    }
}



public class Tester
{
    public static void main(String[]args){
        A a = new B(14);
        System.out.print(a.num);

    }
}

The output of this is: 222.

My question is why is 222 and not 14? I did put constructor inside B that gets int, and I put that int(14) in a b constructor. So why do I get the result as if I used empty A contractor? Can anyone please explain me the logic of this?

Thanks!

Avishay28
  • 2,288
  • 4
  • 25
  • 47

1 Answers1

0

because you have two variables num and as you upcasting your object to A you are using variable from class A which holds only default value

user902383
  • 8,420
  • 8
  • 43
  • 63
  • I don't down casting the object to B? – Avishay28 Feb 15 '16 at 16:40
  • Still i'm not really sure I understand this. a count as B or A? – Avishay28 Feb 15 '16 at 16:52
  • @Avishay28 your class A has field 'num' now when you create class B which extends class A, class B inherit field `num` from class A . By creating field 'num' in class B you are hidding original field. So as fields aren't polymorphic in Java, then calling a.num access variable from class A. when you downcast it to B, then you will access variable from class B which is set to 14 – user902383 Feb 15 '16 at 17:06
  • So I access variable from class B, as you say (I down cast A), and is set to 14, so why the output is 222? – Avishay28 Feb 15 '16 at 17:10
  • @Avishay28 you upcast your variable to A, when you do `A a = new B(14);` and as you do that, you can access only fields and methods declare in class A. As methods are polymorphic, you will call methods defined in class B, and as fields aren't you will access fields from class A – user902383 Feb 15 '16 at 17:17