2

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?

Community
  • 1
  • 1
turtlesoup
  • 3,188
  • 10
  • 36
  • 50

4 Answers4

4

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.

sp00m
  • 47,968
  • 31
  • 142
  • 252
4

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 {
}
Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
1

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.

Valentin V
  • 24,971
  • 33
  • 103
  • 152
0

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.

Julien
  • 1,302
  • 10
  • 23