- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we use "this" keyword in a static method in java?
The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference).
Example
public class Sample{ static int num = 50; public static void demo(){ System.out.println("Contents of the static method"); } public static void main(String args[]){ Sample.demo(); } }
Output
Contents of the static method
The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.
Example
public class Sample{ static int num = 50; public static void demo(){ System.out.println("Contents of the static method"+this.num); } public static void main(String args[]){ Sample.demo(); } }
Compile time error
Sample.java:4: error: non-static variable this cannot be referenced from a static context System.out.println("Contents of the static method"+this.num); ^ 1 error
- Related Articles
- Why can't we use the "super" keyword is in a static method in java?
- Can we return this keyword from a method in java?
- Can we call a method on "this" keyword from a constructor in java?
- Is it possible to use this keyword in static context in java?
- Can we call methods using this keyword in java?
- Can we override the static method in Java?
- Can a "this" keyword be used to refer to static members in Java?\n
- Can we override a private or static method in Java
- Can we declare a static variable within a method in java?
- Does static factory method internally use new keyword to create object in java?
- How can we use this and super keywords in method reference in Java?
- Can we overload or override a static method in Java?\n
- static Keyword in Java
- Can we call Superclass’s static method from subclass in Java?
- Can We declare main() method as Non-Static in java?

Advertisements