Struct Like Objects in Java

Struct like objects in Java

This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.

In practice, most fields have simple getters and setters. A possible solution would look like this:

public property String foo;   
a->Foo = b->Foo;

Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller

Creating struct like data structure in Java

A struct in C just like a class in Java and much more powerful, because class in Java can contain method, and C++ does. You create a new class. For example :

   class Employee {
private String name;
private int code;

// constructor
public Employee(String name, int code) {
this.name = name;
this.code = code;
}

// getter
public String getName() { return name; }
public int getCode() { return code; }
// setter

public void setName(String name) { this.name = name; }
public void setCode(int code) { this.code = code; }
}

And when you want to create multi employees, create array just like in C:

Employee[] arr = new Employee[100];  // new stands for create an array object
arr[0] = new Employee("Peter", 100); // new stands for create an employee object
arr[1] = new Employee("Mary", 90);

Does Java support structs?

Java definitively has no structs :)
But what you describe here looks like a JavaBean kind of class.

What's the difference between an object and a struct in OOP?

Obviously you can blur the distinctions according to your programming style, but generally a struct is a structured piece of data. An object is a sovereign entity that can perform some sort of task. In most systems, objects have some state and as a result have some structured data behind them. However, one of the primary functions of a well-designed class is data hiding — exactly how a class achieves whatever it does is opaque and irrelevant.

Since classes can be used to represent classic data structures such as arrays, hash maps, trees, etc, you often see them as the individual things within a block of structured data.

An array is a block of unstructured data. In many programming languages, every separate thing in an array must be of the same basic type (such as every one being an integer number, every one being a string, or similar) but that isn't true in many other languages.

As guidelines:

  • use an array as a place to put a large group of things with no other inherent structure or hierarchy, such as "all receipts from January" or "everything I bought in Denmark"
  • use structured data to compound several discrete bits of data into a single block, such as you might want to combine an x position and a y position to describe a point
  • use an object where there's a particular actor or thing that thinks or acts for itself

The implicit purpose of an object is therefore directly to associate tasks with the data on which they can operate and to bundle that all together so that no other part of the system can interfere. Obeying proper object-oriented design principles may require discipline at first but will ultimately massively improve your code structure and hence your ability to tackle larger projects and to work with others.

Making/Initializing Array of Struct Like Objects in Java

That is how it should behave. Java isn't going to guess that the array should be filled with elements instantiated with the zero-argument constructor. If you want to fill the array, all you need to add is:

for (int i = 0; i < rangeNodes.length; i++)
rangeNodes[i] = new IntRange();

You could explicitly initialize each element, but this is the cleanest solution.

Is it possible to use struct-like constructs in Java?

You're basically asking whether you can use a C-specific solution to a problem in another language. The answer is, predictably, 'no'.

However, it is perfectly possible to construct a class that takes a set of bytes in its constructor and constructs an appropriate instance.

class Foo {

int someField;
String anotherField;

public Foo(byte[] bytes) {
someField = someFieldFromBytes(bytes);
anotherField = anotherFieldFromBytes(bytes);
etc.
}
}

You can ensure there is a one-to-one mapping of class instances to byte arrays. Add a toBytes() method to serialize an instance into bytes.

Is there something like C's struct in Java?

Unfortunatly there is no decent support to read binary structured data in java.

This example reads image header into a byte array and assembles the required information.

Why is using a class as a struct bad practice in Java?

There's an argument that classes should either be "data structures" (i.e., focus on storing data with no functionality) or "functionality oriented" (i.e., focus on performing certain actions while storing minimal state). If you follow that argument (which makes sense but isn't always easy to do) then there is nothing necessarily wrong with that.

In fact, one would argue that beans and entity beans are essentially that - data containers with getters and setters.

I have seen certain sources (e.g., the book "clean code") arguing that one should avoid methods with multiple parameters and instead pass them as a single object with getters and setters. This is also closer to the "smalltalk model" of named parameters where order does not matter.

So I think that when used appropriately, your design makes sense.

Equivalent of C++ struct in Java

To write a structure in Java, similar would be a class. So yes, you somewhat answered your question.

I believe that this is a better detailed explanation:
Creating struct like data structure in Java



Related Topics



Leave a reply



Submit