java - 在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中实现同样的目标
解决方案
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 fields
)self
:bulk
和norm
。六种公共方法 ( )
public
:getSelf
、setSelf
、getBulk
、setBulk
和.getNorm
setNorm
这样,从ZeroToOne
类创建的所有对象都将具有self
,bulk
并且norm
能够存储不同的值,能够在调用其定义的方法时进行修改或查询:
setSelf
// ⇨允许您将ASSIGN设置为/setBulk
/ ( int)类的一个对象。setNorm
self
bulk
norm
ZeroToOne
getSelf
// ⇨允许您CONSULT获取getBulk
//类的一个对象。getNorm
self
bulk
norm
ZeroToOne
声明和创建一个类的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
推荐阅读
- c - C Linked List char数组输入复用问题
- java - 递归保留值中的局部变量?
- django - django rest框架列表更新api视图
- python - R 到 Python/Numpy 线性回归曲线
- typescript - 如何在 Ionic 3 的后台按顺序依次上传文件(图像)?
- c# - 在c#中从位图转换为ImageBitmap的问题
- javascript - 带有 typescript 的 create-react-app 将函数编译成非常奇怪的东西
- javascript - 单击按钮后在 GoogleMaps 上选择一个点
- javascript - javascript:如何将变量转换为返回原始值的同名函数
- html - CSS“子”选择器的行为类似于“后代”选择器