When I first started coding in Java I struggled to understand the differences betweenstatic
andfinal
, what were they or when to use them, so I decided to write a short summary for the newcomers.
To the point! Let's see how we can use them in our code.
Thefinal
keyword
It can be used in variables, methods, and classes.
Final variables
Final variables are intended to serve asconstants, values that shouldn't (and won't) ever change:
classCar{publicfinalintnumberOfWheels=4;}
Even if we wanted to modify this value, the compiler would throw an error:
CarmyCar=newCar();myCar.numberOfWheels=1;>>>ThefinalfieldCar.numberOfWheelscannotbeassigned
Final methods
Final methods cannot be overridden by any subclasses. Assume the classCar
and the classSedan
:
classCar{publicfinalintgetNumberOfWheels(){return4;}}classSedanextendsCar{// This won't work because the method getWeight is final!@OverridepublicdoublegetNumberOfWheels(){return3;}}
This can be useful in cases that, as the one described, the result or the behavior of the method should not change when called from subclasses.
Final classes
Using the final keyword in a class prevents it from being extended:
finalclassPear{privatedoubleweight;privateStringcolor;}// This won't work because the Pear class is final!classMagicalPearextendsPear{}
Thestatic
keyword
In Java,static
simply implies that the field or method is not going to change its value or behavior across all the instances of an object.
In other words, that means that we can call it without instantiating the object we are using.
So, if we define a CurrencyConverter:
classCurrencyConverter{publicstaticStringEUR="€";publicstaticdoubleconvertDollarsToEuros(doubleamountInDollars){doublerate=0.90;returnamountInDollars*rate;}}
We can then call theconvertDollarsToEuros
method without declaring any instance of the class:
System.out.println(CurrencyConverter.convertDollarsToEuros(5.43D));CurrencyConverterconverter=newCurrencyConverter();System.out.print(converter.convertDollarsToEuros(5.43D));>>>4.887>>>4.887
In the same way, we can call the static variableEUR
without instantiating the object and,unlike final variables, we can evenmodify it.
But that we can do it doesn't mean that we should, as its considered bad practice to modify static variables.
That's why more often than not, static variables are also final:
publicstaticfinalStringEUR="€"
Hopefully, we now understand a little bit better the differences between those two keywords as well as when to use them.
Suggestions and constructive criticism are always welcome!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse