Struct in Java

Last Updated On Thursday 4th Nov 2021

Struct Java

  • The struct is a keyword for creating a structure that contains variables, methods, different types of constructors, operators, etc.
  • It is similar to classes that hold different types of data and has a value type.
  • It creates objects which require less memory.

Actually a struct in C++ is a class (e.g. you can define methods there, it can be extended, it works exactly like a class), the only difference is that the default access modfiers are set to public (for classes they are set to private by default).

Java Struct

	class Point {
    private double x;
    private double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return this.x;
    }

    public double getY() {
        return this.y;
    }

    public void setX(double x) {
        this.x = x;
    }

    public void setY(double y) {
        this.y = y;
    }
}
	

java struct example

	Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));
	

It is acceptable to use public fields when the class represents just a data structure

	class Point {
    public double x;
    public double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
	

The drawback of creating public fields in objects is that you have no control over the values that are set to it.

Use the JUnion Plugin to Simulate a Struct in Java

We can also use the Project JUnion plugin. Here we get software that helps us to create struct by using @Struct annotation.

With Project JUnion you can use structs in Java by annotating a class with @Struct annotation

struct in java example

	@Struct
class Member {
  string FirstName; 
  string LastName;  
  int BirthYear; 
}
	

References