简体   繁体   中英

Can't call a static method from another class to main class

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

  1. 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());

  2. 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 :

  1. I have created a package name stackoverflow
  2. Two class callerClass and NewTriangle in package stackoverflow.
  3. Make an import of class NewTriangle in callerClass.
  4. using the Static function by NewTriangle.getnumberOfTriangles()

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.

  1. A static method belongs to the class rather than object of a class.
  2. A static method can be invoked without the need for creating an instance of a class.
  3. static method can access static data member and can change the value of it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM