Java® classes can contain member variables called fields which might have public or private access.
To access public data fields, which your code can read or modify directly, use the syntax:
object.field
To read from and, where allowed, to modify private data fields, use the accessor methods defined by the Java class. These methods are sometimes referred to as get and set methods.
For example, the java.awt.Frame
class has
both private and public data fields. The read accessor method getSize
returns
a java.awt.Dimension
object.
frame = java.awt.Frame; frameDim = getSize(frame)
frameDim = java.awt.Dimension[width=0,height=0]
The Dimension
class has public data fields height
and width
.
Display the value of height
.
height = frameDim.height
height = 0
Set the value of width
.
frameDim.width = 42
frameDim = java.awt.Dimension[width=42,height=0]
To list the public fields of a Java object, call the fieldnames
function. For example, create
an Integer
object and display the field names.
value = java.lang.Integer(0); fieldnames(value)
ans = 'MIN_VALUE' 'MAX_VALUE' 'TYPE' 'SIZE'
To display more information about the data fields, type:
fieldnames(value,'-full')
ans = 'static final int MIN_VALUE' 'static final int MAX_VALUE' 'static final java.lang.Class TYPE' 'static final int SIZE'
A static data field is a field that applies
to an entire class of objects. To access static fields, use the class
name. For example, display the TYPE
field of the Integer
class.
thisType = java.lang.Integer.TYPE
thisType = int
Alternatively, create an instance of the class.
value = java.lang.Integer(0); thatType = value.TYPE
thatType = int
MATLAB® does not allow assignment to static fields using
the class name. To assign a value, use the static set
method
of the class or create an instance of the class. For example, assign value
to
the following staticFieldName
field by creating
an instance of java.className
.
objectName = java.className; objectName.staticFieldName = value;