1
package morepackage;

public class Subclass extends Superclass {
  public static void main ( String args[] )
  {
    String name = super.text;//error in this line
    String name1 = Superclass.text;//no error in this line
  }}

The code of the superclass is:

public class Superclass {
  static String text = "flowers";
}

Can anyone please tell me why the line String name = super.text is showing error

While the line String name1 = Superclass.text; is not showing error ?

StuartLC
  • 104,537
  • 17
  • 209
  • 285
arpansen
  • 205
  • 1
  • 13

3 Answers3

1

The method main is static, there is no such thing as super inside a static method.

fernandohur
  • 7,014
  • 11
  • 48
  • 86
1

main is a static method and thus not able to access references to this and super.

In any event, even if this you did obtain an instance to a Subclass (e.g. via new), it is not good practice to access static members of classes via class instance, hence the access Superclass.text is the correct way to refer to "Flowers".

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
0

super refers to the parent class of the actual object. In the main method there is nothing like "actual object" because it is a static scope.

The Superclass's attribute text is defined as static so you can access it throught it class name inside the static main method.

Don't you confound class with object (or instance).

Paco Abato
  • 3,920
  • 4
  • 31
  • 54