"Hello, Amigo! Today, Bilaabo will talk about the order in which variables are initialized."
Imagine you're looking at some code. What values do the variables get?
Code
class Cat
{
public int a = 5;
public int b = a + 1;
public int c = a * b;
}
Code
class Cat
{
public int a = getSum();
public int b = getSum() - a;
public int c = getSum() - a - b;
public int getSum()
{
return a + b + c;
}
}
"Is that really allowed?"
"Of course. The order in which a class's member methods and fields are declared is not important."
A class is loaded from top to bottom, so it's important that a field only accesses other fields that have already been loaded. In the example, b can access a, but it doesn't know anything about c.
"And what will happen?"
"When variables are created, they get default values."
Code | What really happens |
---|---|
|
|
|
|
"Holy moly! It's so simple. Thank you, Bilaabo. You're a real friend!"
"Hooray! Bilaabo has a friend!"
GO TO FULL VERSION