Create a Struct In Java Like C++

2019-08-27 04:53发布

问题:

i want to create an struct in java , like c++ :

struct MyStruct {
    int x;
};
#include <iostream>
int main() {
    MyStruct Struct;
    Struct.x = 0;
    std::cout << Struct.x;
    return 0;
}

can anyone help me ?

回答1:

You can use a class, which functions similarly to a struct in C++.

For example, a C++ point struct may look like

typedef struct __point {
   int x, y;
} point;

A Java point class has the form

final class Point { 
    private final double x;    // x-coordinate
    private final double y;    // y-coordinate

    // point initialized from parameters
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    // accessor methods
    public double x() { return x; }
    public double y() { return y; }

    // return a string representation of this point
    public String toString() {
        return "(" + x + ", " + y + ")";
    } 

}

We may then call the following:

Point q = new Point(0.5, 0.5);
System.out.println("q  = " + q);
System.out.println("x = " + q.x());


回答2:

public class ircodes {
    public ircodes(String msg_id, String node_id, String frequency, String data) {
        this.hdr = new msg_hdr(4 + data.length(), Integer.parseInt(msg_id), Integer.parseInt(node_id));
        this.frequency = Integer.parseInt(frequency);
        this.data = data;
    }

    public class msg_hdr {
        int msg_len;
        int msg_id;
        int node_id;

        public msg_hdr(int msg_len, int msg_id, int node_id) {
            this.msg_len = 12 + msg_len;
            this.msg_id = msg_id;
            this.node_id = node_id;
        }
    }
    msg_hdr hdr;
    int frequency;
    String data;

    public ByteBuffer serialize() {
        ByteBuffer buf = ByteBuffer.allocate(hdr.msg_len);
        buf.putInt(hdr.msg_len);
        buf.putInt(hdr.msg_id);
        buf.putInt(hdr.node_id);
        buf.putInt(frequency);
        buf.put(data.getBytes());
        return buf;
    }
}


回答3:

Java doesn't have structs like C or C++, but you can use Java classes and treat them like a struct. On top of that, you can of course declare all its members as public. (to work exactly like a struct)

class MyClass
{
    public int num;
}

MyClass m = new MyClass();
m.num = 5;
System.out.println(n.num);

One of the differences between a struct and a class is that a struct do not have methods. If you create a class without methods, it will work like a struct.

However, you can always put in methods (getters and setters) and set the variables as private like this (it doesn't hurt).

class MyClass
{
    private int num;
    public void setNum(int num){
        this.num = num
    }
    public int getNum(){
        return num
    }
}

MyClass m = new MyClass();
m.setNum(5);
System.out.println(n.getNum());

Java doesn't have structs, but a Class can do exactly the same things a struct does.



标签: java struct