Reputation: 11
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());
}
Upvotes: 0
Views: 1213
Reputation: 1005
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 :)
Upvotes: -1
Reputation: 201439
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!
Upvotes: 1
Reputation: 649
You have to write the name of the class before :
NewTriangle.getnumberOfTriangles()
Upvotes: -1
Reputation: 1105
If your main method is in a different class, then you need to specify the classname while calling the static method, i.e., NewTriangle.getnumberOfTriangles()
Upvotes: 3