Qaisar Mahmood
Qaisar Mahmood

Reputation: 72

Could not access the class attribute inside the class using 'this' keyword

public class Class1{  
      static  int x = 5;        
        public static void fmethod(){           
            this.x;
        }
}
  1. Compiled error : non-static variable this cannot be referenced from a static context this.x

Upvotes: 1

Views: 70

Answers (1)

nik0x1
nik0x1

Reputation: 1461

By using the this keyword we are accessing an attribute of an current object.

A field defined as static does not belong to a specific object, but to a class, and to access it you can use the following construction:

Class1.x

An alternative solution would be to define the field and the method as non-static and access it using the proposed construct:

this.x

Upvotes: 1

Related Questions