Data Fields ofJavaObjects
Access Public and Private Data
Java®classes can contain member variables calledfieldswhich might have public or private access.
To accesspublicdata fields, which your code can read or modify directly, use the syntax:
object.field
To read from and, where allowed, to modifyprivatedata fields, use theaccessormethods defined by the Java class. These methods are sometimes referred to asgetandsetmethods.
For example, thejava.awt.Frame
class has both private and public data fields. The read accessor methodgetSize
返回一个java.awt.Dimension
object.
frame = java.awt.Frame; frameDim = getSize(frame)
frameDim = java.awt.Dimension[width=0,height=0]
TheDimension
class has public data fieldsheight
andwidth
. Display the value ofheight
.
height = frameDim.height
height = 0
Set the value ofwidth
.
frameDim.width = 42
frameDim = java.awt.Dimension[width=42,height=0]
Display Public Data Fields ofJavaObject
列出一个Java obje的公共字段ct, call thefieldnames
function. For example, create anInteger
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'
Access Static Field Data
Astatic data fieldis a field that applies to an entire class of objects. To access static fields, use the class name. For example, display theTYPE
field of theInteger
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 staticset
method of the class or create an instance of the class. For example, assignvalue
to the followingstaticFieldName
field by creating an instance ofjava.className
.
objectName = java.className; objectName.staticFieldName = value;