That's Allowed in Java!?26 Apr 2015
Sometimes you think you know a programming language really well. When I first looked at the Java code below, I thought there was NO WAY this code could compile.
I thought the declaration of myString in doWork would complain about a variable with the same name already being accessible. But I was wrong. It compiles and runs.
How? Why? This works because of variable shadowing. You have probably already seen variable shadowing in action in constructors and probably didn’t bat an eyelid.
That said, I’m not going to run out and use this newfound knowledge. Variable shadowing makes code confusing. My inner compiler (the thing that told me this would never compile) will help me steer clear of using this language feature. But given how programmers sometimes like to
show off discuss the finer points of languages, this knowledge isn’t totally useless.
Kudos to Abubakkar Rangara for helping me get to the bottom of my Java knowledge gap!