Chapter:Classes - final members - Exercises

From Juneday education
Jump to: navigation, search

Exercises on final variables and methods

Let's go back to our Member class. We added a variable separator that we turned into a static variable, in the previous chapter. Why should anyone, including ourselves, be able to change it? We (the authors) see no reason to be able to change it. So let's make the variable "unchangeable". This opens up for the possibility to also make it public - but that's a decision we leave up to you.

Having a public static final variable is considered OK for constant values. It is, however, not always the case that we want to expose such constants to the world. Knowing the name of constants could create a dependency to your class.

It is, however quite common with public static final constants. See for instance the three thousand or so public static final values defined in the Java API.

Q1

Make it impossible to change the separator variable. Do this by using the keyword final. Also make sure that the method setSeparator(String separator) is present in the code. Compile. Does it work?

Expand using link to the right to see a suggested solution/answer.

Change the separator declaration to look something like this:

  private static final String separator = ";";

It does not compile since we have a method setSeparator(String separator) that alters (changes) the values of separator which we have made final.

Q2

Remove the setSeparator(String separator) and compile again. Compile and explain why this happens.

Expand using link to the right to see a suggested solution/answer.

Now it compiles again. So we can't change, or even provide a method with which we can change, the value of a final variable.

Q3

There is a coding convention which says that final static variables (constants) should be named with all upper case letters with underscore as word separator if the name consists of several words. What should you rename separator to? (No underscore is needed, since it consists of only one word)

Expand using link to the right to see a suggested solution/answer.

SEPARATOR

Links

Further reading

Where to go next

Next chapter is: Classes_-_Using_packages

« PreviousBook TOCNext »