Java - Access method in every classes and packages - java

I wrote a method public static String timestamp() in a class called Utilities, which I want to call in every System.out.println().
Can you tell me how I can call this method in a different package? For example when I have package XY, with the class XY in it, then I can't call the timestamp() method, which is in the root src folder.

You need to use the whole class name, so as your class is called "Utilities":
Utilities.timestamp();
Will call your method. Remember to import your "Utilities" class at the top of your calling class.
Alternatively, if you want to just call:
timestamp();
You can statically import the class:
import static com.foo.Utilities

You need to import the package containing the class containing the timestamp() method. If you haven't declared a package for the class, you should do it now. After importing you can just use Utilities.timestamp() to call it.
If you're unfamiliar with packages in general, you should see the Oracle tutorials: http://docs.oracle.com/javase/tutorial/java/package/

So, more often than not, utility classes are declared as static. I'll give you an example.
Example
public class Utilities
{
public static String timestamp()
{
// Return timestamp.
}
}
Then in your XY class, you need to import your Utilities class, and you can access it as follows.
Utilities.timestamp();

You can call it using:
Utilities.timestamp();
from any class. Remember to import the Utilities class

It's static so you can just call Utilities.timestamp();

Related

Why did my import fail in Java?

I hava a StdDraw.java under the same folder of my working file, and picture() is a method within StdDraw.java.
However, I failed adding this line to import the method, suggesting by
package StdDraw does not exist
import StdDraw.picture
How could I possibly do that? Using package? Setting path? Or any modifications? I came from python and find it a little bit weird.
You can't import non-static methods (only classes and static members), and you don't have to!
If both your classes live in the default package then you should be able to do the following without any import statements :
myStdDrawObject.picture(); // if picture is non-static
or
StdDraw.picture(); // if picture is static
Note also, that you can't use static imports on classes that live in the default package.
If you are importing into the class which is there in same package then we no need to use any import.
if you want import mthods into the class use like below. You no need to put method name at the time of the import.
import packagename.StdDraw;
After importing your class, all non static methods of the class are available into the imported class.
when should you use static import? 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.
Read more about static import:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
When importing the package you do not need to import non static methods. You can read on Java - Packages here. It is easily explained and I found it useful when learning the same concept.
Even if you do not include import for the class which is present in the same folder, then also you can create object and call method of that class and also static methods.
You can create object and call the non-static methods.
StdDraw drawObj = new StdDraw();
drawObj.picture(); // if picture is non-static method
For static method, you can call it using class name only.
StdDraw.picture(); // if picture is static method.
What I recommend is to read up on packages and how code is organized in java. It is in someway similar to python, where a directory structure is used, but more to it in java. Maybe this will help
Java Tutorial- Packages

How do I avoid unnecessary class references in Java?

I have two java classes (.java files). I want to be able to create new instances of an object in one class that were defined in the other class, without referencing the class name each time. In C# there are #using and includes, but I am only able to use import <pre-compiled code> in java. Is there a way to do this:
import TestClass;
and then simply call a function inside it without using
TestClass.TestFunction()
every time? I simply need to have all of my functions and objects to be separate from my Main class.
Assuming TestFunction is a static method in TestClass, you can use a static import:
import static TestClass.TestFunction;
// or
import static TestClass.*;
and then call it without using the class qualifier:
TestFunction(...);
Note this can lead to confusing/hard-to-read code – use static imports sparingly.
If you're using netbeans then you won't be finding any issue during the import of any java classes. And yeah that's true you can have only "pre-compiled classes" as import statement. If you are running on notepad then you need to compile your independent classes first and then your dependent classes. And if you use Netbeans or Eclipse or any other IDE then you do not have to worry they will manage by themselves, you just have to use proper package and class names
You can have two types of imports
import package1.Class1;
import static package1.Class2;
With the first one you can create object of Class1 (or any other class if present in Class1) and invoke the methods
With the second one you can directly call the static methods of Class2 without referencing it with classname
Updated
See tutorials on packages in JAVA

Do we need to import a package only to create an object or to call a method from that object as well?

class TestFormat
{
public static void main(String[] args)
{
System.out.println("hello");
}
}
In the above simple code the out object is of type java.io.PrintStream. The println() method is also of class PrintStream. PrintStream resides in a different package then java.lang which is the default java package.
My question is how are we able to use method of a class from a package(java.io) we have not even imported? Granted that the object of that class is already provided to us but does that means that we need to import a package only to create an object of a class from that package and not to use its methods afterwards?
Thnax in advance!
You misunderstand what import does.
Yes, you can use a class and its methods without an import statement. It means that you'll have to type out java.io.PrintStream instead of using the short name PrintStream.
The class loader searches the classpath for a .class file when you first use a class; import has nothing to do with this process. It's just a way to save you from having to type out the fully resolved class name.
You can write Java successfully and never use an import if you wish. You just need to be a good touch typist.
import is just saves you from typing total path if you import that class you are able to write PrintStream otherwise you have to write complete path java.io.PrintStream

Importing own file into Java class

Okay, not sure if this would work.. but would it be possible, to use my own Java file that has certain required methods in it, to be imported into my Java class just like any other import? Or does it have a special way?
If your Java file contains a proper Java class enclosing the methods mentioned above, and it is visible to the compiler (i.e. either its source file is on the compiler source path or its class file is on the compiler classpath), you can just import it like any other classes.
Have you tried it? Do you have any specific problem?
If that method is static and visible in your scope, you can use import static. It will make the imported static method look like it is in your class. For example, if your code parse a lot of integers, you can use
import static Integer.parseInt;
And then the parseInt method will be visible and invokable directly:
int parsed = parseInt("123");
That is only required if your other class is in a different namespace. if they are in the same namespace (this includes the default empty namespace), and you 'tell' the compiler about both files, you don't need to use import statements.
If however class A is in namespace org.example.stuffA, and you want to use it in class B in org.example.stuffB, you'll need to use a import org.example.stuffA.A statement, or hard-link it in the document (new org.example.stuffA.A() for example).
In the namespaces example, you still need to make sure the compiler is able to find the required classes. In both cases you also need to make sure the methods you need are of the correct permission type, they would probably need to be public.
You Can use Static methods or by create Object of it & Use.
public class abc
{
public static MyMethod()
{
// ..
}
}
public class pqr
{
abc.MyMethod();
}
Another Way
public class abc
{
public void MyMethod()
{
// ..
}
}
public class pqr
{
abc Obj=new abc();
Obj.MyMethod();
}

Non-class functions in Java

I'm mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated with any class that I can invoke from anywhere in my project (#include of some sort necessary?).
I know I can make a public static function of a class and invoke it as Class.someFunction();. I would like to just have someFunction(); I'm not sure if this is possible in java, or what the syntax for it is.
You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:
import static x.y.Class.someFunction; // or x.y.Class.*;
...
// some code somewhere in the same file
someFunction();
However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.
P.S. This also works for static fields.
You could use a static import:
import static com.example.MyUtilityClass.*; // makes all class methods available
// or
import static com.example.MyUtilityClass.myMethod; // makes specified method available
You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).
Here's a related question about when it's advisable to use this.
Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.
Although, you still need to import the Utility class.
Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.
Hope this helps.
thanks....!!!
Yeap import static..
For instance:
import static java.lang.Math.max; // Allowing to use max method anywhere in the source
class SomeClass {
int m = max( 1, 2 );// m now is 2 due t Math.max( int, int )
}

Categories