0

The below two situations also have a same variable a in super class and subclass . Does any problem will be raised if using these coding style? thanks

situation 1

public class A {
    int a;
    void meth(int b) {
        a+=b;
    }
}

public class B extends A {
    int a;
    void meh2(int b) {
        a+=b;
    }
}

situation 2

public class A {
    int a;
    void meth(int b) {
            a+=b;
    }
}

public class B extends A {
    int a;
    void meh2(int b) {
        a+=b;
    }
    B(int a) {
        this.a=a;
    }
}
0

3 Answers 3

2

Depends on how you classify it as a problem. It will work as I believe you will expect. In short, it's an ill-advised practice, but the 'a' in class 'A' (with or without the 'this.') will never be seen or used by class 'B' due to the overshadowing.

1
  • 1
    yes, and I would call it a problem. I avoid variable shadowing (same var name in inheritance) because it just gets so confusing in the usage! My take is, avoid having same var names in these cases.
    – aishwarya
    Dec 5, 2011 at 2:46
0

Any style that could create confusion should be avoided, because inevitably it will create confusion.

My advice here would be to remove the declaration of int a from class B - let it use the a field from class A

0

This does not explicitly cause an error. What you are doing is taking away your access to the a in class A and instead giving access only to a in class B

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.