External Interfaces/API    

Accessing Private and Public Data

Java API classes provide accessor methods you can use to read from and, where allowed, to modify private data fields. These are sometimes referred to as get and set methods, respectively.

Some Java classes have public data fields, which your code can read or modify directly. To access these fields, use the syntax object.field.

Examples

The java.awt.Frame class provides an example of access to both private and public data fields. This class has the read accessor method getSize, which returns a java.awt.Dimension object. The Dimension object has data fields height and width, which are public and therefore directly accessible. The following example shows MATLAB commands accessing this data.

The programming examples in this chapter also contain calls to data field accessors. For instance, the sample code for Example - Finding an Internet Protocol Address uses calls to accessors on a java.net.InetAddress object.

Accessing Data from a Static Field

In Java, a static data field is a field that applies to an entire class of objects. Static fields are most commonly accessed in relation to the class name itself in Java. For example, the code below accesses the WIDTH field of the Frame class by referring to it in relation to the package and class names, java.awt.Frame, rather than an object instance.

In MATLAB, you can use that same syntax. Or you can refer to the WIDTH field in relation to an instance of the class. The example shown here creates an instance of java.awt.Frame called frameObj, and then accesses the WIDTH field using the name frameObj rather than the package and class names.

Assigning to a Static Field

You can assign values to static Java fields by using a static set method of the class, or by making the assignment in reference to an instance of the class. For more information, see the previous section, "Accessing Data from a Static Field". You can assign value to the field staticFieldName in the example below by referring to this field in reference to an instance of the class.


  Finding the Public Data Fields of an Object Determining the Class of an Object