Shadowing a variable
I was fiddling witht the new Eclipse IDE 3.2 (nothing to do with
this post). I was experimenting, creating my own version of the
singleton ConnectionManager class that I got from my senior during my
training with my previous company. I had a lot of doubts about
inheritance in my mind, especially about member variables. Since member
variables are logically not overidden(there'sno point of doing so
according to experts), I wondered what would happen if I declared a
member in an abstract class, and declare it again in base class. So I
tried something like this:
class A
{
protected int p;
public int getP()
{
return p;
}
}
class B extends A
{
protected int p;
public int getP()
{
return p;
}
}
Now this is absolutely legal,
it will compile and will not make any runtime exception(I think). But I
was told that this is a bad practice and could lead to hard-to-find
bugs. If somebody needs an explanation, when an instance of class B is
created and the getP() method is invoked the p that is returned is that
of B's. Unless of course you call super.getP(). Plain ol polymorphism.
The point in this post is that this is a bad practice and should be
avoided at all cost.