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

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

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

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!

You have to write the name of the class before :
NewTriangle.getnumberOfTriangles()

You can do something like this:
Example using :
I have created a package name stackoverflow
Two class callerClass and NewTriangle in package stackoverflow.
Make an import of class NewTriangle in callerClass.
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.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
I hope I was helpful :)

Related

Can we create an object of the class in which main function is defined in Java?

Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Yes? The main method is just an entry point. The class is like any other, except it has an additional public static method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.

How to get class name for static main method

I need class name for public static void main method. Eg for my class name is GetClassName so output statement was not printed GetClassName
public class GetClassName {
public static void main(String[] args)
{
System.out.println(getClass().getName().toString());
}
}
You can get it from static context, unless explicitly specifying the class. For example:
System.out.println(GetClassName.class.getName());
should be
System.out.println(GetClassName.class.getName());
No need for .toString() method, method already return String
You can try like this:
GetClassName.class.getName();
This will give you class name with package as well. OR
GetClassName.class.getSimpleName();
This will give you only class name.
IDEONE DEMO
Just use GetClassName.class.getName(). The whole point of a static method is that the class it's on will never change.

Calling a static method of an abstract class in another class

I have a class Employee
import javax.swing.*;
public abstract class Employee {
public static void searchEmp(int id) {
JOptionPane.showMessageDialog(null, "done");
}
}
Now I have another class test:
public class `test` {
public static void main(String args[]) {
searchEmp(2);// here my programme give error
}
}
I want to call the searchEmp() which is part of Employee from a class test but it gives an error. Please suggest any solution without inheritance.
You have to call Employee.searchEmp().
The static method searchEmp() is still a member of the class Employee and you must make a static call via its class.
Also the class Employee must be visible to the class test, otherwise you have to import it. I assume the two classes reside in the same package so this will not be a problem in your case.
Static methods and properties are bound to class. So you need to use ClassName.methodName or ClassName.propertyName.
Employee.searchEmp();
Your Test class doesnt have a static searchEmp(int) method, thus the error:
searchEmp(2);// here my programme give error
should be
Employee.searchEmp(2);
static methods are called using ClassName.staticMethod()

Use Functions in different classes in Java without collecting it in a class as methods

I have some functions collected as methods in a class called func. I use those methods quite often in different classes. Is there a way in java to call those functions without creating a new object or calling it like this: func.myFunction();?
I want: myFunction();
There are two issues:
you can't call non-static methods without having an instance of that class and
you can't directly call static methods without mentioning the class name.
The first one is easy to solve: if your method doesn't actually use any non-static members (fields or methods) of the class, then simply adding the static keyword enables you to call it without an instance of the class:
// in YourClass:
public static void yourMethod() {
//stuff
}
// somewhere else:
YourClass.yourMethod();
And about the second item: I kind-of lied there, you can do that, but you need a static import:
// at the beginning of your .java file
import static yourpackage.YourClass.yourMethod;
// later on in that file:
yourMethod();
Also: there are no functions in Java, only methods.
Yes, you can mark the methods as static, and use static imports.
Example:
pkg/UtilFunctions.java
package pkg;
public class UtilFunctions {
public static int sum(int i1, int i2) {
return i1 + i2;
}
}
Test.java
import static pkg.UtilFunctions.*;
class Test {
public static void main(String[] args) {
int i = sum(5, 7); // Calls UtilFunctions.sum(...)
}
}
Make them static like public static int myFunction(); and then make static import: import static myclass:
Foo.java:
class Foo {
public static int method() {return 42;}
...
}
Bar.java
import static Foo.*;
...
System.out.println(method());
You can use a static import.
For example this:
import java.lang.Math;
...
System.out.println(Math.abs(-1.4));
and this:
import static java.lang.Math;
...
System.out.println(abs(-1.4));
produce the same result.

java basics static method

can a static method be invoked before even a single instances of the class is constructed?
absolutely, this is the purpose of static methods:
class ClassName {
public static void staticMethod() {
}
}
In order to invoke a static method you must import the class:
import ClassName;
// ...
ClassName.staticMethod();
or using static imports (Java 5 or above):
import static ClassName.staticMethod;
// ...
staticMethod();
As others have already suggested, it is definitely possible to call a static method on a class without (previously) creating an instance--this is how Singletons work. For example:
import java.util.Calendar;
public class MyClass
{
// the static method Calendar.getInstance() is used to create
// [Calendar]s--note that [Calendar]'s constructor is private
private Calendar now = Calendar.getInstance();
}
If you mean, "is it possible to automatically call a specific static method before the first object is initialized?", see below:
public class MyClass
{
// the static block is garanteed to be executed before the
// first [MyClass] object is created.
static {
MyClass.init();
}
private static void init() {
// do something ...
}
}
Yes, that is exactly what static methods are for.
ClassName.staticMethodName();
Yes, because static methods cannot access instance variables, so all the JVM has to do is run the code.
Static methods are meant to be called without instantiating the class.
Yes, you can access it by writing ClassName.methodName before creating any instance.
Not only can you do that, but you should do it.
In fact, there are a lot of "utility classes", like Math, Collections, Arrays, and System, which are classes that cannot be instantiated, but whose whole purpose is to provide static methods for people to use.
Yes, that's definitely possible. For example, consider the following example...
class test {
public static void main(String arg[]) {
System.out.println("hello");
}
}
...if then we run it, it does execute, we never created a instance of the class test. In short, the statement public static void main(String arg[]) means execute the main method without instantiating the class test.

Categories