moh hossain
moh hossain

Reputation: 11

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());
}

Upvotes: 0

Views: 1213

Answers (4)

Abhi
Abhi

Reputation: 1005

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 :)

Upvotes: -1

Elliott Frisch
Elliott Frisch

Reputation: 201439

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!

Upvotes: 1

Korteby Farouk
Korteby Farouk

Reputation: 649

You have to write the name of the class before :

NewTriangle.getnumberOfTriangles()

Upvotes: -1

curlyBraces
curlyBraces

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

Related Questions