Main Content

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.Frameclass has both private and public data fields. The read accessor methodgetSize返回一个java.awt.Dimensionobject.

frame = java.awt.Frame; frameDim = getSize(frame)
frameDim = java.awt.Dimension[width=0,height=0]

TheDimensionclass has public data fieldsheightandwidth. 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 thefieldnamesfunction. For example, create anIntegerobject 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 theTYPEfield of theIntegerclass.

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 staticsetmethod of the class or create an instance of the class. For example, assignvalueto the followingstaticFieldNamefield by creating an instance ofjava.className.

objectName = java.className; objectName.staticFieldName = value;

See Also