jmasterx
jmasterx

Reputation: 54123

How do structures work in Java?

In c++, one could simply do something like this:

struct GraphObject {
Color color;
double value;
String name;
};

However in Java, I can't simply do this, I only see creating a class just for this as an option. What I do not like about that is then I need to drag around GraphObject.java and Graph.java (since Graph will hold an ArrayList of GraphObject. Is there a way to put the object class in with Graph.java or is this simply impossible/bad practice?

Thanks

Upvotes: 1

Views: 361

Answers (4)

Thomas Weber
Thomas Weber

Reputation: 1005

You will want to make a static nested class:

public class Graph {
    static class GraphicObject {
        Color color;
        double value;
        String name;
    }
}

If you omit the static keyword, each instance of Graph will automatically create an instance of GraphicObject. Moreover the references will be tied together allowing synthetic access to the outer class using the this. Non-static (inner) classes are rarely needed and add a lot of cost to object creation.

For more information on the differences between static and non-static nested classes: http://blogs.oracle.com/darcy/entry/nested_inner_member_and_top

Upvotes: 6

corsiKa
corsiKa

Reputation: 82579

You can make a class inside another class if you want to.

class Graph {

    class GraphicObject {
        Color color;
        double value;
        String name;

        // You can omit this, and treat it just like a struct if you want
        GraphicObject(Color c, Double b, String n) {
           // ...
        }
    }

    List<GraphicObject> myObjects();
    // other things about Graph here, as normal

}

Upvotes: 3

MBCook
MBCook

Reputation: 14504

You can do it. If that's the only file you use the class in, it's not a problem. If you use it in other files, it will still work but it's not considered good practice.

Usually you'd do it as an inner class.

Upvotes: 1

Alex
Alex

Reputation: 3652

You could make it a nested class if appropriate for your design.

Upvotes: 7

Related Questions