Instance/Static initializers
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
The code below does not compile because of the PUBLIC modifier. If you remove PUBLIC the compile is happy however is you include any modifier the compiler barks at you.
Can anyone explain why this is not possible?
public class Test {
{
public int g = 0;
if(g > 0)
System.out.println("Can compile");
}
}
------------------
Can anyone explain why this is not possible?
public class Test {
{
public int g = 0;
if(g > 0)
System.out.println("Can compile");
}
}
------------------
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
OK, this is a bit of a guess but I think it's a good guess - I'd be grateful if anyone could confirm it. Because you're declaring g inside the initialiser, it's effectively a method variable and you can't put access modifiers in front of method variables.
So what you're probably wanting to do is this:-
public class Test {
public int g;
{
g = 0;
if(g > 0)
System.out.println("Can compile");
}
}
So g is now a class member variable.
Hope this helps,
Kathy
So what you're probably wanting to do is this:-
public class Test {
public int g;
{
g = 0;
if(g > 0)
System.out.println("Can compile");
}
}
So g is now a class member variable.
Hope this helps,
Kathy
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
java compiler has problem with you are declared int i as public
there is no problem with public class Test//
Remember you never declare local varible(in method,in static block or simple block) with any access modifier.
bye.......................bye
there is no problem with public class Test//
Remember you never declare local varible(in method,in static block or simple block) with any access modifier.
bye.......................bye
oluwayomi adegoju
Greenhorn
Posts: 15
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Thanks very much. I now understand why.
posted 24 years ago
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Hi! oluwayomi,
i think it just scope problem. in instance initialize block your variable g just work within his {}. there4 u cant declare public g variable....hope this help.
if m i wrong plz tell me.
thanx
Aftab
i think it just scope problem. in instance initialize block your variable g just work within his {}. there4 u cant declare public g variable....hope this help.
if m i wrong plz tell me.
thanx
Aftab
Keep Simlling
| catch it before it slithers away! Oh wait, it's a tiny ad: Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing |









