![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Advertisements