I've been working on some problems from Project Euler, and, in the process, have written a lot of useful methods (in Java) that I might like to use in other Java projects. I want to be able to call them in the way that you call a function from java.lang.math, so if I had a method primeFactor() I could call it using MyMathMethods.primeFactor(number). How would I go about this? Would I make some kind of package that I could import? Would I make a superclass that includes all my useful math-y functions and have whatever class I'm working with in a new project extend that? There are probably multiple ways to do this, but I don't know what is best. Thanks in advance.
Mark your utility methods as public static. Package your classes containing those utility methods in a jar. Add/Refer that jar in your project, where you want to use the. Then in your code you can call them in a static way lke : MyUtilityClass.myUtilityMethod();
The best thing for this situation is to work in meaningful packages and make their jar
You can create a package like
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Also on classes
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
You can import them like
import animals.*; OR be more specific import animals.MammalInt;Now you can make the jar file , import it in your project and use its methodYou can eaisly do it by this commandjar cmf MyJar.jar Manifest.txt MyPackage/*.class
For more details about jar creation please see thisAs a side note: Be carefull about visibility of members and functions while packaging itBecause there usage and accessibility matters a lot while we are using them
You could create separate java project with your util classes only and then create jar file and import into any another project.
Simply instantiate the class. Like your example, if you had a class MyMathMethods with the function primeFactor(number) then at other classes, simply instantiate it with something like private MyMathMethods myMathMethods;. Now, to call the function simply do myMathMethods.primeFactor(number); You may need to import its package as well.
False understanding of packages is any class defined within a package is visible to all other classes. Not true from my experience. If you have classes containing utility style methods you want to make available in another class? Simply declare a new instance of the class in the class you need the method in. Like... private MathUtilsClass mathUtilsClass = new MathUtilsClass(): Then any method you want to call from this class uses the new identifier, e.g. mathUtilsClass.greatFunction(); This is stupidly easy and should solve your problem.
Related
I have two packages. The first one contains an empty interface and a class implementing it in a single file ("IThing" and "Thing"). The second one contains another Interface ("IThingUser") which has a function returning an object of the type "Thing".
When both files are part of the same package everything works fine, but if they are in two separate packages the one in package2 cannot access the class defined in the first package.
Package1 contains the following file :
package project.package1;
public interface IThing {
}
final class Thing implements IThing {
private int thingField;
public int thingFieldGetter(){
return thingField;
}
}
And package2 has :
package project.package2;
import project.package1.IThing;
public interface IThingUser {
public IThing someFunction(); // Works fine
public Thing anotherFunction();
// "Thing" is not recognized when the two files are in separate packages.
}
Why does this happen ? Is there a way to fix this issue while keeping this architecture ?
PS : I know the structure of this does not make much sense but I did not code package1 and I have to use it as-is.
The problem is that project.package1.Thing is not visible outside the package project.package1, but public classes must be defined in their own files.
Class Thing has package-private visibility. You wouldn't be able to access it outside project.package1 package until it will be implemented as
public final class Thing implements IThing
How can I refer to a Java class in stdlib1.jar when the directory structure is like this? How to write the import statement?
I want to call a method under stdlib1.jar, I have configured it.
The classes are in the default package. According to this answer, it is not possible to import classes from the default package. So, they have to be moved to another package or you have to use reflection.
You call a method from a class and not from a package.
You don't need to specify the jar when you call a method from a class belonging to it. Which matters is your jar is in the classpath
In your screenshot if the lib makes part of the classpath folders, you can import and use classes from it in your code.
Here the classes of your jar use the default package (no package name) which seems weird for a third-party library. Default package is not recommended since it doesn't allow to naturally reference and use the classes of the archive from the client code.
I am not sure you are using the correct version of the jar. Look at that :
http://grepcode.com/snapshot/repo1.maven.org/maven2/com.googlecode.princeton-java-introduction/stdlib/1.0.1
This contains classes in the edu.princeton.cs package :
With package, you could declare this :
For example :
You could create a class like that and use BinaryIn like that:
package main;
import edu.princeton.cs.BinaryIn;
public class MyClass(){
public static void main(String args[]){
BinaryIn in = new BinaryIn();
}
}
Context: Two classes from different packages (Second class in second package inherits class in first package) are connected through inheritance and made a method call to subclass from parent class.
What I did:
Written two classes in two different notepad files and trying executing one after other but was not possible for me to execute and showing error messages and my classes are as follows:
package first;
import second.Sample1;
public class Sample {
public static void main(String a[])
{
Sample1 s=new Sample1();
s.dis(1);
}
package second;
import first.Sample;
public class Sample1 extends Sample{
public void dis(int i)
{
System.out.println(i);
}
}
In Eclipse, it is giving output as 1 but in what order I should execute these codes using notepads files. Observed that compiling these classes in any order giving error messages.
Thanks much. :)
You created a cyclic package dependency, which is not a good idea.
Your base class Sample doesn't have to know anything about its sub-classes, and when it does, it is usually a sign of bad design.
Just move the main method to Sample1, and Sample class won't have to import second.Sample1.
I have a JAR file that I'm using and I want to modify one of the files inside it. In a nutshell I have
public class ClassB {
public void printMethod(){
ClassA A = new ClassA();
A.printout();
}
}
public class ClassA {
public void printout(){
System.out.println("1234");
}
}
and I want to change ClassA's printout method to
public class ClassA {
public void printout(){
System.out.println("abcd");
}
}
I know you cannot modify a JAR without unpacking/rebuilding it and for this, let's say I can't do that. Is there a way to make modifications to ClassA without actually touching the current ClassA? My approach is to have a new class inherit from ClassA with an overridden method and then have a new class inherit from ClassB that calls the Inherited ClassA
public class InheritedClassA extends ClassA{
#Override
public void printout(){
System.out.println("abcd");
}
}
public class InheritedClassB extends ClassB{
#Override
public void printMethod(){
InheritedClassA A = new InheritedClassA();
A.printout();
}
}
I don't like this approach though because in my actual JAR, so many classes are using ClassA that its a nightmare trying to correctly do this with all of them, which then all require the same process on them. I know you cannot overload/overwrite a whole class which is basically what I want to do. Is there another way to do this?
EDIT
To make it even harder, I cannot download any new frameworks or software or anything.
I can only provide pointers as I never felt the need for it.
What you are referring to is called "Bytecode enhancement", and yes there are several frameworks to achieve it.
BCEL - http://commons.apache.org/bcel/
ASM - http://asm.ow2.org/
Usually, java developers prefer to use the inversion of control pattern. This allows the code to configure itself at runtime via a configuration file - See Spring IoC for more details.
One option which may not be feasible would be to create a new version of ClassA, package it up in its own jar file, and put that ahead of the original version in your classpath.
However, this is a pretty odd scenario - why can you not update the existing jar file? Even if that means a bit of extra work, it's likely to be much cleaner in the long run than any other approach.
I have three .java files and I need to get them to work together. I think that I need to add all the classes to a main method but I am not sure if this is correct and if I just add the name of the class and the format.
I figured it out, the three files had a package listed at the top of each. I created a new Java project in Eclipse and then a source folder and in the source folder I created a package with the name that they all referenced. Now it runs. Thanks for all of you help for the Eclipse/Java beginner.
You are right: what you think is not right :P
Java can find the classes that you need, you can just use them straight away. I get the feeling that you come from a C/C++ background (like me) and hence think that you will need to "include" the other classes.
java uses the concept of namespaces and classpaths to find classes. Google around for it.
A little example of how variety of classes can be used together:
// A.java
public class A {
public void sayIt() { sysout("Said it by A!"); }
}
// B.java
public class B {
public void doIt() { sysout("Done it by B!"); }
}
// MainClass.java
public class MainClass {
public static void main(String[] args) {
A aObj = new A();
B bObj = new B();
aObj.sayIt();
bObj.doIt();
}
}
Note that there are no includes/imports here because all of the classes are in the same namespace. If they were not, then you'd need to import them. I will not add a contrived example for that coz its too much to type, but should google for it. Info should be easy enough to find.
Cheers,
jrh
If they are in the same package you do not need to do anything, as they are automatically imported for you, but otherwise you'll need to add import statements before your class declaration.
Once this is done, you can reference static members directly ie ClassB.staticMethod(); or instantiate the class ie ClassB classb = new ClassB();
But honestly, if you are this confused, you need to spend some more time doing tuturials.
http://eclipsetutorial.sourceforge.net/totalbeginner.html
http://download.oracle.com/javase/tutorial/getStarted/cupojava/index.html
http://www.freejavaguide.com/corejava.htm
I am not sure what you mean by "adding classes to a main method". If you want to make use of several classes inside your Java program, just import the needed classes/packages at the beginning and create an instance of each class as you go along.
I learned this from a beginner program called Jeroo
Basically if I want to create a new "Jeroo", I would write the following on my Main method:
Jeroo Bob = new Jeroo();
{ methods... }
So basically:
[class] [customnameofclass] = new [class]