Tutorial :Why can't I put my functions in another class?



Question:

I created a new class called "Tools" inside my "com.example.hello" workspace.

Tools.java:

public class Tools {      public static String getSource (String theurl) {          URL u;          InputStream is = null;          DataInputStream dis;          String s;          String ss = "";          try {             u = new URL(theurl);             is = u.openStream();         // throws an IOException             dis = new DataInputStream(new BufferedInputStream(is));             while ((s = dis.readLine()) != null) {                ss = ss +  s;             }          } catch (MalformedURLException mue) {          } catch (IOException ioe) {          } finally {             try {                is.close();                return ss;             } catch (IOException ioe) {             }          }           return ss;       }           }  

From that exact namespace (com.example.hello), there is a .java file in there...and I want to use getSource.

I tried import com.example.hello.Tools.*

But for some reason, I can't use getSource?

I just want to be able to call "getSource" from my other classes that are in the same folder.


Solution:1

You want:

import static com.example.hello.Tools.*;  

to use getSource() without writing Tools.getSource(). Of course if you want to write Tools.getSource() just use a standard import:

import com.example.hello.Tools;  


Solution:2

Do you need to add the following? (Asking because I don't see it in your example.)

package com.example.hello;  

It's not enough to place the file in the proper folder structure; you have to provide a package declaration at the top of the file.


Solution:3

import static com.example.hello.Tools.*;  

Here is a pointer to static import.

EDIT : You can also call as Tools.getSource(). Since Tools is in the same package you don't need to import it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »