Reputation: 4094
I believe the Java way is to keep external classes in separate files. So I've ended up with a directory structure like the following
/main/main.java
/main/libs/class01.java
/main/libs/class02.java
/main/libs/class03.java
Which would be fine but some of the classes are really puny little things, for example if all the classes were just
package libs;
import java.util.*;
public class class01 {
public Integer idno;
public String name;
public class01() {}
idno = 1;
name = "First";
}
}
Then separate files seem like they could get a bit excessive. I'm wondering if there is a way to combine them into a single file similar to the way that you can do in .Net C# with namespaces like the following
using System;
using System.Data;
namespace allClasses {
public class class01 {
public Integer idno;
public String name;
public class01() {}
idno = 1;
name = "First";
}
}
public class class02 {
public Integer idno;
public String name;
public class02() {}
idno = 2;
name = "Second";
}
}
public class class03 {
public Integer idno;
public String name;
public class03() {}
idno = 2;
name = "Third";
}
}
}
Which I can use in my main as if they were all separate
using System;
using allClasses;
namespace main_module {
class main {
static void Main(string[] args) {
class01 newClass01 = new class01();
class02 newClass02 = new class02();
class03 newClass03 = new class03();
}
}
}
I'm sorry for comparing the two it's just that .Net C# is the best example I can show of what I am trying to achieve. I don't know a way of doing this yet in Java, some guidance would be very much appreciated
Upvotes: 0
Views: 53
Reputation: 233
You can declare them as public static class
within another public class.
E.g.
public class Util {
public static class A {}
public static class B {}
}
Then in your main class you can reference them as:
new Util.A();
This will help you combine source code into a single class, but as @oleg-cherednik mentioned, when compiled there will be several separate class files.
Upvotes: 1