首页 > 解决方案 > 在java中创建一个对象并分配项目

问题描述

Javascript一个可以创建一个对象,如:

       newdata: {
            zero_to_one: {self: 0, bulk: 0, norm: 0},
            one_to_2: {self: 0, bulk: 0, norm: 0},
            two_to_4: {self: 0, bulk: 0, norm: 0},
            over_four: {self: 0, bulk: 0, norm: 0},
        }

在javascript中修改数据很简单,只需调用this.zero_to_one.self =2

我怎样才能在java中实现同样的目标

标签: javaobject

解决方案


Java中对象的声明和创建

精简版

JS到Java的转换如下:

JS

newdata: {
            zero_to_one: {self: 0, bulk: 0, norm: 0},
            one_to_2: {self: 0, bulk: 0, norm: 0},
            two_to_4: {self: 0, bulk: 0, norm: 0},
            over_four: {self: 0, bulk: 0, norm: 0},
}

JAVA

// ZeroToOne.java
public class ZeroToOne {

    int self; // Type self
    int bulk; // Type bulk
    int norm; // Type norm

    /**
     * GETTERS AND SETTERS
     */

    public int getSelf() {
        return self;
    }

    public void setSelf(int self) {
        this.self = self;
    }

    public int getBulk() {
        return bulk;
    }

    public void setBulk(int bulk) {
        this.bulk = bulk;
    }

    public int getNorm() {
        return norm;
    }

    public void setNorm(int norm) {
        this.norm = norm;
    }

}

以同样的方式,您将能够使用one_to_2,two_to_4和来做到这一点over_four

这称为简单的对象创建,也就是我们在 java中所说POJO的。

ℹ️ 更多信息:
Plain_old_Java_object

大版本

按照前面的例子:

   public class ZeroToOne {

    // Attributes of the ZeroToOne class
    private int self; // Type self
    private int bulk; // Type bulk
    private int norm; // Type norm

    // Methods of the ZeroToOne class

    /**
     * GETTERS AND SETTERS
     */
    public int getSelf() {
        return self;
    }

    public void setSelf(int s) {
        this.self = s;
    }

    public int getBulk() {
        return bulk;
    }

    public void setBulk(int b) {
        this.bulk = b;
    }

    public int getNorm() {
        return norm;
    }

    public void setNorm(int norm) {
        this.norm = norm;
    }
}

请注意,在类 body中,键之间{}已定义:

  • attributes(也称为private fieldsselfbulknorm

  • 六种公共方法 ( ) publicgetSelfsetSelfgetBulksetBulk和.getNormsetNorm

这样,从ZeroToOne类创建的所有对象都将具有self,bulk并且norm能够存储不同的值,能够在调用其定义的方法时进行修改或查询:

  • setSelf// ⇨允许您将ASSIGN设置/setBulk / ( int)类的一个对象。setNormselfbulknormZeroToOne

  • getSelf// ⇨允许您CONSULT获取getBulk//一个对象getNormselfbulknormZeroToOne

声明和创建一个类的ZeroToOne对象:

    ZeroToOne callZeroToOne; // Declaration of variable p1 of type Person
    ZeroToOne zOne = new ZeroToOne (); // Create an object of the Person class

此外,可以在一行中表示相同的内容:

ZeroToOne callZeroToOne = new ZeroToOne();

修改值

以及在哪里直接修改你的值self必须通过以下方式进行:

    ZeroToOne callZeroToOne; // Declaration of variable p1 of type Person
    ZeroToOne zOne = new ZeroToOne (); // Create an object of the Person class
    zOne.setSelf (2); // We modify the value
    System.out.println (zOne.getSelf ()); // Impression of the result

我们会得到什么

> 2

推荐阅读