I wrote down a simple program to demonstrate the use of the static keyword. I've also typed a method to calculate the square of the variable and have initialized the value of the static variable in the main class.
class staticdemo{
public static int stvar;
void square(int stvar){
System.out.println("" + stvar*stvar);
}
}
public class statictest {
public static void main(String args[]){
staticdemo.stvar = 10;
int s = staticdemo.stvar;
square(s); //HERE IS WHERE I GET THE ERROR!
}
}
the exact error i get is " the method square(int) is undefined for the type statictest"
how can i execute the method with a static variable?
你的方法也应该是静态的
The problem isn't that you're passing a static field (not variable) into the method. It's that you're trying to call an instance method without an instance.
Either:
Make square
static
as well, so you can call it from main
, or
Create an instance in main
to call it on:
new staticdemo().square(staticdemo.stvar);
I'd also strongly urge you not to use the same name for a static field ( stvar
) and a function parameter ( stvar
in square
). It's just asking for confusion and trouble.
Also suggest following standard Java naming conventions, even in your own test code, but particularly when asking others for help.
So perhaps:
class StaticDemo {
public static int stvar;
public static void square(int s) {
// ^^^^^^ ^
System.out.println("" + s * s);
// ^ ^
}
}
public class StaticTest {
public static void main(String args[]) {
StaticDemo.square(StaticDemo.stvar);
// ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
}
}
Or alternately:
class StaticDemo {
public static int stvar;
public void square(int s) {
// ^
System.out.println("" + s * s);
// ^ ^
}
}
public class StaticTest {
public static void main(String args[]) {
new StaticDemo().square(StaticDemo.stvar);
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
}
}
This method must be static
void square(int stvar)
if you want to call it from an static context
another more elegant and OOP way would be to declare an object of the class, encapsulate its members by declaring them private
ie
public static void main(String args[]){
staticdemo.stvar = 10;
int s = staticdemo.stvar;
staticdemo foo = new staticdemo();
foo.square(s); //HERE will work fine!
}
You cannot call the nonstatic method directly. You have to create an object for the staticdemo class then you can call the method using the oobject. Inside the main method enter staticdemo st=new staticdemo(); st.square(s);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.