Instance Initializer
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
and not this
I am unable to figure out if instance initializers requires variable to be declared before it can be used then why first part of my code compiles?
-
1 -
-
Number of slices to send:Optional 'thank-you' note:
-
-
In your second example here s1 is used at left hand side of assignment so no problem It compiles but on the very next line this use is not allowed so gives compile time error.
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
As you are new here, I edited your post to put code tags around your code. Always UseCodeTags when posting code with proper indentations. See now It looks more readable
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
In case of assignment we can use instance variables but as a statement we cannot i guess.
Helped me alot;
cheers.
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
I always thought that this rule was weird.
So, you are not allowed to access a variable before it is declared. I get that. However, you can assign the variable? Isn't assigning a variable accessing a variable? Heck, isn't it also changing the value of the variable too?
Henry
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
If you want to use that instance variable in print statement then need to use with this keyword likeMuhammad Rehan wrote: but as a statement we cannot i guess.
which will print "someText" as value of String s1.
Yes.Henry Wong wrote:However, you can assign the variable? Isn't assigning a variable accessing a variable? Heck, isn't it also changing the value of the variable too?
Before declaration we can assign the instance variable using It''s name only i.e. left side of assignment operator but when we need to read It may be for some operations like printing Or arithmetic operation in that situation we have to use this keyword with instance variable. In case of static variable we have to use ClassName.staticVariable
8.3.3. JLS 8 wrote:Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. Specifically, it is a compile-time error if all of the following are true:
1. The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;
2. The use is a simple name in either an instance variable initializer of C or an instance initializer of C;
3. The use is not on the left hand side of an assignment;
4. C is the innermost class or interface enclosing the use.
If we remove/comment line of codes causing CE then run this code, we get following output:
no1: 0
no1: 1
no1: 120
no2: 200
| rubbery bacon. crispy tiny ad: Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing |








