Question

I am a new-bee to Java.

I know, even a sub-class can not refer a non-static member of a base class directly. like,

class BaseClass
{
int id;
public void testMethod()
{
    System.out.println("Hello");
}
}
public class Test1 extends BaseClass
{
public static void main(String[] args)
{
    System.out.println("ID : " + id);
}
}

This will give us an error "Cannot make a static reference to the non-static field id"

But, in case of abstract class, we can do it.

abstract class MyAbstractClass
{
int id;
public void setId(int id)
{
    this.id = id;
}
}

public class SubClass extends MyAbstractClass
{
public void testMethod()
{
    System.out.println("ID Value : " + id);
}
public static void main(String[] args)
{
    SubClass obj = new SubClass();
    obj.setId(1);
    obj.testMethod();
}
}

I was wondering how and why is it possible in case of abstract class. Appreciate your answers. Please be gentle, I am a new-bee to java. :)

Was it helpful?

Solution

The problem you stated does not depend on abstract classes but on static and nonstatic contexts. You simply make two different calls to the instance variable.

The first example tries to access id from a static context which is not allowed and you get your error (Cannot make a static reference to the non-static field id).

public static void main(String[] args)
{
    System.out.println("ID : " + id);
}

In the second example, you create an instance of your class and from within this instance you are able to access id. This is a reference from a nonstatic context.

public void testMethod()
{
    System.out.println("ID Value : " + id);
}

So you achieve the same for your first example, if you create an instance like in the second and access id from a nonstatic method..

OTHER TIPS

Cannot make a static reference to the non-static field id

This error appears because you want to access to a non-static field inside a static method. And that's what you're doing here: main method is static, but id is not.

public static void main(String[] args) {
    //here you don't create an instance of the class
    //you cannot access to id directly
    System.out.println("ID : " + id);
}

You need to create an instance of the class to access to its non-static fields, as you did in the second example, regardless if you're extending from other (abstract) class or not.

public static void main(String[] args) {
    //here you create an instance of the class
    SubClass obj = new SubClass();
    obj.setId(1);
    obj.testMethod();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top