1

I have a class A with a variable bool var = true and a getter method getVar(). I'm trying to create a class B that extends A and redefines var to bool var = false. The code:

public class A{
    protected boolean var = true;
    public boolean getVar(){
        return var;
    }
}

public class B extends A{
    protected boolean var = false;
}

The problem is that if I execute:

B b_class = new B();
System.out.println(b_class.getVar());

I obtain true and I don't undestand why. What I'm doing wrong?

1
  • You can't do B.getVar(), since the method isn't static. I assume you mean b_class.getVar() and fixed it. Commented Jan 15, 2012 at 18:47

5 Answers 5

7

You don't "inherit" variables; B.var merely hides A.var, but only in B. You are calling getVar(), a method in A, which sees A.var, which is true.

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

Comments

3

You are declaring a new var field in B that is hiding A.var. Try this instead:

public class B extends A {
    public B() {
        var = false;
    }
}

Comments

2

You shouldn't be creating a new instance variable in your overridden class, because it can't be seen by the super class (A), and therefore when getVar() is called, it will return the value it can see. You should instead be setting the value of var in the constructor to be what you want.

public B() {
    var = false;
}

Comments

1

Variable initialized in the super class can’t be changed like this. You have already declared protected boolean var = true. So, no matter what you do in extended class it will always show you true.

Comments

0

GetVar isn't defined in B so polymorphism jumps to A where var is true.

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.