class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
In the above code, I do not understand the use of creating object d of Demo class with static keyword preceding it. If I eliminate the static keyword, it shows an error. Actually, I was going through anonymous inner class concept and got stuck here. Need help.... Can anyone please explain it?
A "static" object is unique; it belongs to the class rather than the instance of the class. In other words, a static variable is only allocated to the memory once: when the class loads.
A static block, or static initialization block, is code that is run once for each time a class is loaded into memory. It is useful for setting up static variables or logging, which would then apply to every instance of the class.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With