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.

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

1 Comment

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.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.