Final variable manipulation in Java

前端 未结 11 698
无人及你
无人及你 2020-11-28 23:28

Could anyone please tell me what is the meaning of the following line in context of Java:

final variable can still be manipulated unless it\'s immut

11条回答
  •  有刺的猬
    2020-11-28 23:44

    If you have a final reference to a Java object you can still manipulate it but cannot change its reference. For instance this code is perfectly legal:

    import javax.swing.JLabel;
    
    class Test1 {
        private final static JLabel l = new JLabel("Old text");
        public static void main(String[] args) {
            System.err.println(l.getText());
            l.setText("New Text");
            System.err.println(l.getText());
        }
    }
    

    But you can't say:

    l = new JLabel("Newest Text");
    

    After the first assignment to l. Note that you can do this though:

    import javax.swing.JLabel;
    
    class Test1 {
        public static void main(String[] args) {
            final JLabel l;
            String s = getArbitaryString(); // Assume this method returns a string
            l = new JLabel(s);
            System.err.println(l.getText());
        }
    }
    

    This can be done because when l is declared it is not assigned to anything not even null. So you are allowed to assign something to it one time only.

    Same thing goes for primitives. You can assign a value to it like this:

    class Test1 {
        public static void main(String[] args) {
            final int i;
            i = 2;
        }
    }
    

    But now you cannot manipulate it further since the only thing you can do to primitive types is to assign values to them.

提交回复
热议问题