Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add classes to a main method

Tags:

java

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.

like image 304
doug Avatar asked May 19 '26 06:05

doug


1 Answers

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

like image 194
jrharshath Avatar answered May 21 '26 18:05

jrharshath