I created a static method which returns a static int in class NewTriangle. But when I try to call it from the main it won't print. It asks to create a method with the same name inside the main.
public class NewTriangle{
public static in numberOfTriangles;
public static int getnumberOfTriangles(){
return numberOfTriangles;
}
}
The code works up until this point. But When I call getnumberOfTriangles() from the main I get an error.
public static void main(String args[]){
System.out.println(getnumberOfTriangles());
}
如果您的主要方法在另一个类中,则需要在调用静态方法时指定类名,即NewTriangle.getnumberOfTriangles()
Assuming the typos in your code are copy and paste errors, you need to either
Use the class name before the method name, you may need to add the class to your import
statements (you need to if it is in a different package)
System.out.println(NewTriangle.getnumberOfTriangles());
Add a static import
of the getnumberOfTriangles
method to your main
class
import static NewTriangle.getnumberOfTriangles;
However, note the caution given in the link:
So when should you use static import? Very sparingly!
您必须在之前编写类的名称:
NewTriangle.getnumberOfTriangles()
You can do something like this:
Example using :
NewTriangle.getnumberOfTriangles() // className.StaticfunctionName()
Working Code:
Class 1 :
package stackoverflow;
public class NewTriangle {
public static int numberOfTriangles;
public static int getnumberOfTriangles() {
return numberOfTriangles;
}
}
Class 2 :
package stackoverflow;
import stackoverflow.NewTriangle;
public class callerClass {
public static void main(String args[]) {
System.out.println(NewTriangle.getnumberOfTriangles());
}
}
Java static method : If you apply static keyword with any method, it is known as static method.
I hope I was helpful :)
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.