class Demo {
void show() {
System.out.println(\"i am in show method of super class\");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base c
Thats because you try to use d
that belongs to object in static method.
You would then have to create that object in main method.
static belongs to class, not object itself.
I want to know the difference between static method and non-static method
The static keyword in Java means that the variable or function is shared between all instances of that class, not the actual objects themselves.
In your case, you try to access a resource in a static
method,
public static void main(String[] args)
Thus anything we access here without creating an instance of the class Flavor1Demo
has to be a static
resource.
If you want to remove the static
keyword from Demo
class, your code should look like:
class Flavor1Demo {
// An anonymous class with Demo as base class
Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args) {
Flavor1Demo flavor1Demo = new Flavor1Demo();
flavor1Demo.d.show();
}
}
Here you see, we have created an instance of Flavor1Demo
and then get the non-static
resource d
The above code wont complain of compilation errors.
Hope it helps!
In order to access methods or variables in main class without creating object in it,here we are defining anonymous inner class where we create object of static type so that its directly accessed from main class without creating the object.
That depends on the context you are in.
The main(String[])
methods is a static methods.
To stay simple, that means it doesn't exist in an instance of Flavor1Demo
, there is no this
here. If you set d
as non-static, it will only exist in an instance of Flavor1Demo
so it can't be access from the main
unless you build a instance first (new Flavor1Demo().d.show();
But a static variable will be link to the class an not an instance, Meaning you can access it from a static context. In you case, the main method.
You get an error by removing static
keyword from static Demo d = new Demo()
because you are using that object d
of class Demo
in main
method which is static
. When you remove static
keyword from static Demo d = new Demo()
, you are making object d
of your Demo
class non-static
and non-static
object cannot be referenced from a static
context.
If you remove d.show();
from main
method and also remove static
keyword from static Demo d = new Demo()
, you won't get the error.
Now if you want to call the show
method of Demo
class, you would have to create an object of your Demo
class inside main
method.
public static void main(String[] args){
Demo d = new Demo();
d.show();
}