Why is it that even if you have declared a private static final variable, a color - defaultC, let's say - then you still cannot use this.defaultC
in the super constructor (i.e. you can only use super(defaultC)
and not super(this.defaultC
) even though it is equivalent to simply defaultC
.
I was simply trying to extend a Tile class to a Wall class and the Wall class I stored all of the necessary private static final
variables for all walls (such as their width and height, another int and the default color), and the Tile class already has some of the variables (but they are protected
not private
). I didn't want the warning Field hides another field
to pop up (because there Tile.java and Wall.java have the same names for many variables), so I used this.
for my private static final variables, and there were errors galore.
It's not particularly troubling (as I simply have a few warnings), but I was simply wondering why. I am guessing that the compiler simply doesn't like it because you cannot reference this
before the supertype, but there are still exactly the same. Has such a feature not been added yet that overlooks such a thing or is there another reason I cannot see that you cannot use super(this.PRIVATE_STATIC_FINAL_VARIABLE);
?
Here we have two things to know,
static
keyword.this
keywordconstructor
in java, there are two types, class
and instance of an class
. We can use a class without creating an instance of it, or after creating a instance of the class itself.
object
is an instance of a class
.
The keyword static
is used with the class. this
is used with instances of class. And this
keyword refers the instance of the class
it is used within.
An instance of an class
(object
) is created after calling the class's constructor
. We can use keyword this
only after creating an instance of class (inside the object).
As the constructor method is called before creating the instance of the class, We can't use this
keyword inside a constructor. That's why you got an error in super(this.defaultC)
but not in super(defaultC)
And you can't use this
keyword inside constructor for PRIVATE_STATIC_FINAL_VARIABLE
as well.
But you are allowed to use PRIVATE_STATIC_FINAL_VARIABLE
without using this
i.e. super(PRIVATE_STATIC_FINAL_VARIABLE)