Question

I am initializing an instance variable through a final method with this code:

public class Whatever {
    private int myVar = initializeInstanceVariable();

    protected final int initializeInstanceVariable() {
        return 10;
    }

    public static void main(String[] args) {
        Whatever myVar2 = new Whatever();
        myVar2.initializeInstanceVariable();

        System.out.println(myVar2.myVar);
    }
}

According to this tutorial:

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

"The method is final because calling non-final methods during instance initialization can cause problems."

My question is: What problem can the method cause without the final keyword? I have ran the code with and without the final keyword and the result was the same, without any compile errors.

Was it helpful?

Solution

first thing as per your current program, no affect of using final or not using it.

because final keyword comes into picture when we go for inheritance.

Now assume we have inherited above class to some other class say AAA.

case 1: if you are not having final method. then all non final methods can be overrided in the subclass and hence there is a chance of modifying your variable value by overrden subclass's method.

Note:here value of a variable of base class can be modified in subclass without knowing it to baseclass.

case 2: if you are having final keyword on a method.

then method can not be overrdien in subclass, if you do so you will get compile time error.

and hence it can not alter your base class variable value.

Note:final should be used if in future you dont want to modify the things.

see below program how it affects without final keyword

package com.kb;

public class Whatever {
    private int myVar = initializeInstanceVariable();

    protected  int initializeInstanceVariable() {
        return 10;
    }

    public static void main(String[] args) {
        Whatever myVar2 = new Whatever();
        myVar2.initializeInstanceVariable();

        System.out.println(myVar2.myVar);

        Whatever var = new AAA();
        System.out.println(var.myVar);
    }
}

class AAA extends Whatever{
    @Override
    protected int initializeInstanceVariable() {
        return 20;
    }
}

one more thing , you dont have to call the method myVar2.initializeInstanceVariable(); again in your scenario.

because you have called a method while doing initializtion of a variable.

so when you access variable, initialized value only you will get

means method will be called automatically and you will get the value.

so below lines will work same if we comment method call as well.

 Whatever myVar2 = new Whatever();
  //  myVar2.initializeInstanceVariable();

    System.out.println(myVar2.myVar);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top