1

Please explain the following behaviour.

class Base
{
    public int num = 3;

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}


class child
    extends Base
{
    public int num = 4;

    public child()
    {

    }

    public child(int i)
    {
        this.num = i;
    }

    public int getNum()
    {
        return num;
    }

    public void setNum(int num)
    {
        this.num = num;
    }
}

public class Main
{

   public static void main(String[] args)
   {

        Base obj2 = new child();
        System.out.println(obj2.num);
        System.out.println(obj2.getNum());

        Base obj3 = new child(10);
        System.out.println(obj3.num);
        System.out.println(obj3.getNum());
    }
}

Output : 3 4 3 10

Here how obj2.num and obj3.num still point to the value 3 which is assigned in the Base class instance variable. Wont it get overidded like the obj2.getNum() and obj3.getNum().

Thanks in advance.

2
  • 1
    possible duplicate of Java "trick", redefining daughter class member Commented Jun 2, 2011 at 9:05
  • Please fix your code. It even won't compile in this form (e.g. what is b() inside your child class?). Commented Jun 2, 2011 at 9:07

1 Answer 1

1

Because the objects are declared with super class type, you get the super member variable value.

If the object was declared with sub class type, the value would be overridden value.

If the Base obj3 = new child(10); is modified to child obj3 = new child(10); the output would be 3 4 10 10

This is well explained here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.