最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oop - Could not access the class attribute inside the class using 'this' keyword - Stack Overflow

programmeradmin1浏览0评论
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
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
Share Improve this question edited Feb 7 at 10:59 Qaisar Mahmood asked Feb 6 at 8:04 Qaisar MahmoodQaisar Mahmood 721 silver badge6 bronze badges 4
  • 3 Well it says, you can't use this in a static context. use the variable name x directly (it will be accessible since it is declared in the same context) or use Class1.x – mr mcwolf Commented Feb 6 at 8:15
  • ok, i can access 'Class1.x' or 'x' but why i could not access with 'this' even i removed 'static' before 'int x'? – Qaisar Mahmood Commented Feb 6 at 9:16
  • 1 this is a reference (pointer) to the specific instance of a class. Therefore this can only be used in specific instances. When you remove static from the declaration of x you make the variable accessible in a specific instance as well (like this). But since you are not creating an instance of Class1 to access it through, you get an error. The same applies to methods declared with static and those without. – mr mcwolf Commented Feb 6 at 9:33
  • 1 my advice is when learning OOP to avoid any use of static. – mr mcwolf Commented Feb 6 at 9:36
Add a comment  | 

1 Answer 1

Reset to default 1

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
发布评论

评论列表(0)

  1. 暂无评论