- 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
Why can't we use the "super" keyword is in a static method in java?
A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference).
Where the "super" keyword in Java is used as a reference to the object of the superclass. This implies that to use "super" the method should be invoked by an object, which static methods are not.
Therefore, you cannot use the "super" keyword from a static method.
Example
In the following Java program, the class "SubClass" contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using this keyword.
class SuperClass{ protected String name; } public class SubClass extends SuperClass { private String name; public static void setName(String name) { super.name = name; } public void display() { System.out.println("name: "+super.name); } public static void main(String args[]) { new SubClass().display(); } }
Compile-time error
SubClass.java:7: error: non-static variable super cannot be referenced from a static context super.name = name; ^ 1 error
- Related Articles
- Can we use "this" keyword in a static method in java?
- Why can't we define a static method in a Java interface?
- Why can't static method be abstract in Java?
- How can we use this and super keywords in method reference in Java?
- Can we override the static method in Java?
- Why we can't initialize static final variable in try/catch block in java?
- super keyword in Java
- Can we return this keyword from a method in java?
- Can we override a private or static method in Java
- Why is the Main() method use in C# static?
- Can we declare a static variable within a method in java?
- Can we access the instance variables from a static method in Java?
- Does static factory method internally use new keyword to create object in java?
- Can we overload or override a static method in Java?\n
- Is it possible to use this keyword in static context in java?

Advertisements