class C{
int a=5;
}
class P{
C c=new C();
}
class d extends P{
void change(){
c.a=7;
new e().show();
}
}
class e extends P{
void show(){
System.out.println(c.a);
}
}
class A{
public static void main(String...args){
new d().change();
}
}
The o/p of this code is 5
But since we have created only one object of class c which is common to both class d and class e the o/p should be 7.
and when I replace precede the statement C c=new C(); with static keyword o/p is 7.
Can any one explain what is happening.
Hi,
First we need to understand the concept of static and instance variables
- Static
This variables are initialized when class is loaded
- Instance
This variables are initialized when Object is created
Class loads only once but we can create multiple objects for a class.
In the above example, C is instance is variable and gets created & initialized in the following cases
- If you create an object for Class p
- If you create an object for any one of the subclass
Now it creates two new objects for P from class d and e
Very clear explanation. This is really an amazing explanation and came to know that why java does not support Multiple inheritance. Dissertation-Time. Keep Posting you are doing a good work.