I am having difficulty in understanding how an instance variable gets initialized when we declare it. Consider the following snippet:
class Rat {
private int val = 20;
}
class Cat {
private Rat rat = new Rat();
}
I am not able to understand how we initialize the instance variables at the time of their declaration within class; aren't these variables supposed to get their "values" or "references" when we actually create an object, for example in main we do:
main() {
Cat cat = new Cat();
}
So that each object have their "own" set of instance variables; and for example to initialize Rat instance variable of Cat, we should do:
cat.Rat = new Rat();
Can anyone help me understand this.