Reputation: 205
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 ?
Upvotes: 1
Views: 186
Reputation: 4065
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).
Upvotes: 0
Reputation: 107357
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".
Upvotes: 1
Reputation: 7154
The method main
is static
, there is no such thing as super
inside a static
method.
Upvotes: 1