I have created a pkg for my regular simple commands. They are non-static, to be more extensible, but somewhat more time-consuming to use because of creating object to use one. My other classes use them.
$ ls *.java
CpF.java IsBinary.java RmLn.java Tools.java
F2S.java IsRoot.java SaveToDisk.java WordCount.java
Filters.java ModRelativePaths.java SetWord.java WordNumber.java
Find.java powerTools.java Sort.java
Which option would you choose to use them easier?
- to develop a small interface like ‘powerTools.java’ for the pkg.
- to create a class with static methods for them.
- to add a static method to each class
- to stop overusing ‘creating too many files’ and centralising some?
- sthing else?
Static VS object-discussion
- How can you get outside methods work like in their own classes without referencing them with their class-name? Not class_name.method(), just method(). Outside methods are from separate pkgs.
Code not Working with Import-static with my class and Pkg
$ cat Test.java
import static a.*;
public class Test
{
public static void main(String[] args)
{
a.printHello();
}
}
$ cat a/Hello.java
import java.io.*;
public class Hello
{
public static printHello(){System.out.println("Hello");}
}
$ javac Test.java
Test.java:1: cannot find symbol
symbol: class a
import static a.*;
^
Test.java:7: cannot find symbol
symbol : variable a
location: class Test
a.printHello();
^
2 errors
$ sed -i 's@a.printHello@printHello@g' Test.java
$ javac Test.java
Test.java:1: cannot find symbol
symbol: class a
import static a.*;
^
Test.java:7: cannot find symbol
symbol : method printHello()
location: class Test
printHello();
At first glance, I bet that none of them maintains any state and thus can be safely declared
static. I also have the impression that each class has actually only one public method which does only one task at once. It also sounds like as if they are tied to a specific platform.If all of above is true, then you have 2 options:
Just group them all in a
public final class PowerToolsclass with aprivateconstructor (so that it cannot be instantiated) andpublic staticmethods, each doing the desired task. You can eventually use the original classname as method name.Define a
public interface PowerToolsso that you can implementLinuxPowerTools,WindowsPowerTools,MacPowerTools, etcetera accordingly and create an abstractPowerToolsFactoryto return the desired implementation automatically based on the current platform (you can use the system propertyos.nameto sniff the current platform).If this is for pure hobby purposes, option 1 would suffice. But option 2 is more “professional”, if you understand what I mean.
Update: as per your update, you can use the
import staticstatement for this. Also see this Sun Tutorial.E.g.
If you have a
com.example.PowerToolsclass containing thepublic staticmethods, then you could import it as follows: