Reputation: 49
At school we use a program doctorjava for coding. Now is it possible to import a class with custom methods that is located in a whole other script and if it is how can you reference it?
edit: I know how to import java classes and packages and was just wondering if it's possible for self made scripts with classes and methods to be imported/referenced like the pre-made ones.
edit 2: I use drJava to make and compile my scripts. The scripts are save as a .java file and the compiled file is saved as .class . I have 2 scripts Mathematics.java
public class Mathematics
{
public static int sum(int a, int b)
{
int result=a+b;
return(result);
}
}
and Test.java
public class Test
{
public static void main(String[] args)
{
int x=12;
int y=36;
//here i want to use the sum method from the mathematics class
}
}
I am new to programming and have only made these to scripts and put them into a folder named test on my desktop. Both scripts are compiled to their respective .class counterpart. What do i need to do now to make the sum method work in the test.java script. I can only use drjava, because this is what we use in school Is what i want even possible and how to do it?
edit3: the problem was only in me forgetting about the main method in the test.java script. But what if the mathematics script isn't in the same folder
but inside a folder that is inside the test folder
directory tree:
test.java
test.class
methods
Mathematics.java
Mathematics.class
in this case the mathematics script is in a subfolder called methods
what does it need to have changed in the script for it to work if possible?
Upvotes: -3
Views: 1341
Reputation: 1
new Mathematics();
new Test();
Maybe That Will Work?
Probally Not Though
Upvotes: -1
Reputation: 49
If the scripts are in the same directory the answer is simple for this example it looks like this
Mathematics.sum(x,y);
If not you are required to create a package by adding this line of code to the top
package methods;
The package name should be the same as your folder name in which it is located Then simply put this line of code to the top of the script with the main method in
import methods.Mathematics;
methods referring to the package name and Mathematics referring to the .java/.class filename
Be cautious since naming the package/script the same as an already existent one in java may lead to errors
Upvotes: 0