Reputation: 3468
I'm wondering if there is a good way to create a new data structure in Java that avoids creating new class file. According to this post, the Java's equivalence to struct in C is simply a class. However I find it redundant to create a whole new file for a class that simply have a couple of public fields, ex: x,y coordinates of a point. In C, the data structure can be defined within the .c file that uses it, which is a lot more simple. Is this actually the only way in Java?
Upvotes: 2
Views: 26071
Reputation: 4202
You have to create a class if you want a data structure. Just to avoid creating multiple .java files, you can put those classes in a single .java file. Assuming, Test.java-
public class Test {
class InnerOne {
}
void m() {
class InnerMost {
}
}
}
class Dummy {
}
class OnMore {
}
Upvotes: 4
Reputation: 48817
You could use inner/nested classes. You'll have only one .java file, but nested classes will all have their own .class file when compiling.
Upvotes: 4
Reputation: 25739
You can create several small, auxiliary classes in one .java file, but they can not be public. So for example you can create a public class, whose name corresponds to a file and a couple of helper classes that are not public.
As for class per data structure in java, java has only one way of creating abstract data types - classes, if you're not satisfied with this - try using other JVM languages, like Scala, it is far more flexible in this regard.
Upvotes: 1
Reputation: 1312
Java is an Object Oriented Programming language, so everything works with classes and you should not try to program with Java as with C.
If you want to define a data structure within a class, you should use InnerClass, there is a good example on the official documentation.
Upvotes: 0