How to define a struct in Java?

There is no syntax directly defining structures in Java. Instead, classes are used to simulate the functionality of structures in Java. Classes can include member variables and methods, which can be used to represent data structures and implement operations.

To define a class to simulate a data structure, you can follow the steps below:

  1. a class that is accessible to all
  2. Define member variables in a class to represent the data of a structure.
  3. Provide a constructor to initialize the member variables.
  4. Provide getter and setter methods to manipulate member variables.
  5. convert to string

Here is an example code to define a class to simulate a Person structure.

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

This way, you can use the Person class to create a struct instance and manipulate its member variables.

Person person = new Person("Alice", 25);
System.out.println(person.getName()); // 输出:Alice
person.setAge(30);
System.out.println(person.getAge()); // 输出:30
System.out.println(person.toString()); // 输出:Person [name=Alice, age=30]

Please note that there are some differences between classes in Java and structures in C++. Classes can contain methods and inheritance, while structures are just a simple type used for organizing data. However, by defining a class that only includes member variables and following the steps mentioned above, you can simulate a data structure similar to a structure in C++.

广告
Closing in 10 seconds
bannerAds