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. :)
syso
is code change. If you will edit, do the indentation only. – Luiggi Mendoza May 15 '14 at 15:09syso
is a shortcut in Eclipse, I find it unreasonable to revert my edit just for that. If you do, then I suggest you take my edit and put it back in but at least leave the other changes intact. – Jeroen Vannevel May 15 '14 at 15:10abstract
. In the first example, you're referencingid
from a static method, and in the second, you aren't. – ajb May 15 '14 at 15:16