Declaration and creation of an object in Java
SHORT VERSION
The conversion of JS to Java would be as follows:
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;
}
}
In the same way you will be able to do it with one_to_2
,two_to_4
and over_four
.
This is called a simple object creation and is what we call POJO
in java.
ℹ️ More information:
Plain_old_Java_object
LARGE VERSION
Following the previous example:
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;
}
}
Note that, in the class body, between the {}
keys have been defined:
Three attributes
(also called private fields
): self
,bulk
and norm
.
Six public methods (public
): getSelf
, setSelf
,getBulk
, setBulk
,getNorm
and setNorm
.
In such a way that all the objects that are created from the ZeroToOne
class will have a self
, bulk
and norm
that will be able to store different values, being able to be modified or consulted when their defined methods are invoked :
setSelf
/setBulk
/setNorm
⇨ allows you to ASSIGN set to self
/ bulk
/ norm
(int) to an object of theZeroToOne
class.
getSelf
/getBulk
/getNorm
⇨ allows you to CONSULT get the self
/ bulk
/ norm
of an object of theZeroToOne
class.
To declare and create an object of class ZeroToOne
:
ZeroToOne callZeroToOne; // Declaration of variable p1 of type Person
ZeroToOne zOne = new ZeroToOne (); // Create an object of the Person class
In addition, the same can be indicated in a single line:
ZeroToOne callZeroToOne = new ZeroToOne();
Modify the value
And where to directly modify the value of self
you will have to do it in the following way:
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
What we would get
> 2