+ 1
Why the class variable can’t be created?
public class Program { public static void main(String[] args) { public class VariableScopeTest { int someInt; public void someMethod () { int someInt; someInt = 5; // Method variable VariableScopeTest.someInt = 7; // class variable } } } }
10 odpowiedzi
+ 2
1)within a method, you can't declare a class as public because the class scope is inside that method only
2)within a non-static method you can't access a non-static variable by class name
i.e. VariableScopeTest.someInt = 7; is wrong
3)as the name of both non-static and local variable is same i.e. someInt , use this keyword to access non-static variable
public class Program
{
public static void main(String args[])
{
class VariableScopeTest
{
int someInt;
public void someMethod ()
{
int someInt;
someInt = 5; // Method variable
this.someInt = 7; // class variable
System.out.println(someInt);
System.out.println(this.someInt);
}
}
new VariableScopeTest().someMethod();
}
}
+ 5
Try to define your class outside the Program class
+ 3
H T,
You can define same variable in multiple methods for example:
method 1(){
int V1;
}
method (){
Int V1;
}
But if you define variable V1 with class scope you can't define V1 again inside method
// you can only do this as a parameter method(int V1){}
+ 2
H T maybe this one can help you
https://code.sololearn.com/c1wNAtWCTo1D/?ref=app
+ 2
Create a method in the VariableScopeTest class and using this pointer assign the value to variable.
+ 1
You can't create two variables with the same name and type in one class.
//If variable Has class scope
0
The error I get is:
Illegal start of the expression.
And the marker shows "public" in "public class VariableScopeTest"
0
One variable is defined in the class and the other one is defined inside the method not the class.
I'm testing the variable scope here.
0
Michal hmmm
So what is the meaning of this expression:
VariableScooeTest.someInt = 7;
0
Rishi Anand Tx a lot sir