This question already has answers here:
Calling static method from another java class
(3 answers)
Closed 1 year ago.
In java, I know I can use methods from other class by creating that class in my main myClass newClass = new myClass() and then use methods by doing myClass.myMethod(), where myMethod() is defined in myClass.java, but what if I want a file named utils.java that contains a bunch of useful methods, I just want to use a function that there's in this file, is this possible? How can I import and use the functions from that file?
You do not need to "import" the functions, you would need just to create a class that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple class.
e.g:
public class Utils
{
public static int doSmth(/* Your parameters here */)
{
// Your code here
}
public static void yetAnotherFunction(/* Your parameters here */)
{
// Your code here
}
}
The most important keyword here is static, to understand it I suggest you check my answer here: when to decide use static functions at java
Then you import this class to any of your other classes and call the static functions, without creating an Object.
import package.Utils;
public class MainClass
{
public static void main(String[] args)
{
Utils.doSmth();
}
}
You can add at the beginning:
import
like-
import utils;
Assuming it is in the same package as the current class
Else it should be:
import <package name>.<class name>
Yes, you can import methods but there are caveats. The methods are defined on a class. The methods are defined as static. The import employs the keyword static. Keep in mind that importing methods directly can create confusion and complicate debugging. Consider importing the class and invoke the method from the class. When/whether defining a utility class makes sense and how to implement them are separate discussions.
package some.path;
public class MyUtils {
public static int add(int x, int y) { return x + y; }
}
To import the method
package some.other.path;
import static some.path.MyUtils.add; // note keyword static here
public class MyClass {
private int a, b;
public int sum() { return add(a,b); }
}
Or, import the class and use the method statically
package some.other.path;
import some.path.MyUtils;
public class MyClass {
private int a,b;
public int sum() { return MyUtils.add(a,b); }
}
Related
I came across this code in hackerrank.com which made me ask this question:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int solveMeFirst(int a, int b) {
return a+b;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
a = in.nextInt();
int b;
b = in.nextInt();
int sum;
sum = solveMeFirst(a, b);
System.out.println(sum);
}
}
why is this possible?
Here, shouldn't it be Solution.solveMeFirst(a,b);
Here, shouldn't it be Solution.solveMeFirst(a,b);
You could call it that, but you certainly don't have to.
The detailed rules for finding the meaning of a name are given in JLS 6.5, but basically the compiler will search through the "current" class (the one that you're calling it from) and all ancestor classes (in this case just Object). It will also use any static imports (which you don't have in this case).
It's just the same with instance methods:
public class Foo {
public void firstMethod() {
secondMethod();
}
private void secondMethod() {
}
}
An instance method can call a static method without any qualification, but a static method can't call an instance method without specifying the instance on which to call the method, e.g.
public class Foo {
public static void staticMethod(Foo instance) {
instance.instanceMethod();
}
private void instanceMethod() {
}
}
It is possible because you are inside the class with the static method you like to invoke.
It is not a special behaviour of the main method.
Any static method can be invoked from the same class both from another static method (like main) but also from a non static method.
There is a situation:
package pak1 contains some class
package pak1;
public class A {
public void g() {}
}
and another package pak2
package pak2;
public class B {
public void f() {
// here I want to call method g() from class A
}
}
Is there any way to call class's A method g() without importing class A (and then new A().g())?
If the method g() was static, I could write
public void f() {
pak1.A.g();
}
you can use fully qualified class name like:
pak1.A a = new pak1.A();
a.g();
Short answer: no, you need to import it.
Having said this, you could still execute A.g() without importing if you use refection API. Keep in mind that would add unnecessary complexity to your code.
As you said its possible only for static imports but otherwise its not possible.
Example of static imports is below where assertEquals is method under Assert class
import static org.junit.Assert.assertEquals;
I found answer from SMA a bit confusing. Here is another way to write it that may help explain the syntax:
// Use Scanner.nextLine() without import
class InputClass {
public static String getString() {
String bob = new java.util.Scanner(System.in).nextLine();
return bob;
}
}
If we use static import for a class, will the compiler generate a class file for statically imported class when compiling the actual class?
Ex:
import static com.x.y.util.B.getIds();
public class A {
...
}
When compiler compiles class A, will it generate class files for B as well?
When you use some type in class using key word import or just by full name to it. You must assure that during compilation time, compiler has that both classes in build path.
The static import allow you to access static members of imported class. Nothing more.
class Bar {
public static int getID() {
return -1;
}
}
And for static import
import static Bar.getID;
class Foo {
private void foo() {
int id = getID(); //instead of Bar.getID();
}
}
Read more on Oracle docs
No, import statement does not cause compiler to generate anything. Think about it: how can compiler generate class if it does not have a source code? Compiler by definition translate source code into executable code (or byte code in case of java).
BTW the syntax of static import in your example is not correct. You should not use () in static import:
import static com.x.y.util.B.getIds;
I am currently working on understanding how to import other classes from a certain package in Java to another package and that certain class.
I was wondering how would I import a method from a certain class in Java to another one since I obviously can't "extend" that class to gain that method since its in some other package.
Example:
package Responses;
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
The question:
How do you import sayHello from the Hello class that's in package Responses.
package Start;
public class Begin {
public static void main(String[] args) {
sayHello();
}
}
I am not extending any classes like I stated above, so please don't suggest that.
Import the class that the function resides in:
import Responses.Hello;
Then you can call the function: Hello.sayHello();
In Java there is no construct to directly import a method, but you can import the class in which it resides.
import static Responses.Hello.sayHello;
Then in your other class you can do:
sayHello();
Note: You can only import methods if they are static.
You either import whole classes (A) or their static members (B).
A:
import responses.Hello;
public class Begin {
String myString = Hello.sayHello();
}
B:
import static responses.Hello.sayHello; // To import all static members use responses.Hello.*;
public class Begin {
String myString = sayHello();
}
What oracle says about the usage of static imports:
So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
Find the whole thing here.
PS
Please use naming convention for your packages:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
That's from here
One way is to make your sayHello() method public static. Like
public class Hello {
public static void sayHello() {
System.out.print("HELLO!");
}
}
Then in your Begin class, you can call sayHello using Hello. Of course you should import that Hello class first if they are not under the same package.
public static void main(String[] args) {
Hello.sayHello();
}
This question already has answers here:
What does .class mean in Java?
(8 answers)
Closed 9 years ago.
For example, in double-checked locking singleton pattern,
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
What's the meaning of "Singleton.class"? Is it an object?
Now I know it's class object, then can we use other objects to synchronize here? Such as "this"?
It represents the Class object of that class. Once you get the Class object, you can do a host of things like get the fields of the class, methods of the class, package of the class and so on.
Most commonly, you will use it to get resources as stream. That is, when you want to retrieve an embedded resource from your jar file. For more detailed information, have a look at the documentation
Run the code below directly at: http://ideone.com/h1czR5
SSCCE
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.lang.reflect.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Class string = String.class;
System.out.println("Package: " + string.getPackage());
System.out.println("Fields: " + java.util.Arrays.toString(string.getFields()));
Method[] methods = string.getMethods();
for(int i = 0; i < 10; i++){
System.out.println(methods[i]);
}
}
}
Output:
Package: package java.lang, Java Platform API Specification, version 1.7
Fields: [public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER]
public boolean java.lang.String.equals(java.lang.Object)
public java.lang.String java.lang.String.toString()
public int java.lang.String.hashCode()
public int java.lang.String.compareTo(java.lang.Object)
public int java.lang.String.compareTo(java.lang.String)
public int java.lang.String.indexOf(java.lang.String,int)
public int java.lang.String.indexOf(int)
public int java.lang.String.indexOf(int,int)
public int java.lang.String.indexOf(java.lang.String)
public static java.lang.String java.lang.String.valueOf(float)
For every class in JAVA, there exists an object. That object is a class object.
This object is singleton Object and can be fetched by Class object=ClassName.class or Class object=Class.forName('ClassName');
Read this for more details.
For your code synchronized (Singleton.class) means you are locking on the class, so that the static member access is sychronized.
You are synchronizing on the "class" object. The class object contains some data "about the class".