Why must I use the “this” keyword for forward references?

后端 未结 5 2061
孤街浪徒
孤街浪徒 2020-12-24 05:11

When I use the this keyword for accessing a non-static variable in a class, Java doesn\'t give any error. But when I don\'t use it, Java gives an error. Why mus

5条回答
  •  渐次进展
    2020-12-24 05:37

    Variables are declared first and then assigned. That class is the same as this:

    class Foo {
        int a;
        int b;
        int c = b;
    
        int var1;
        int var2;
    
        public Foo() {
            a = b;
    
            var1 = var2;
            var2 = var1;
        }
    }
    

    The reason you can't do int a = b; is because b is not yet defined at the time the object is created, but the object itself (i.e. this) exists with all of its member variables.

    Here's a description for each:

        int a = b; // Error: b has not been defined yet
        int a = this.b; // No error: 'this' has been defined ('this' is always defined in a class)
        int b; 
        int c = b;  // No error: b has been defined on the line before  
    

提交回复
热议问题