Accessing and Setting Class and Instance Variables

At this point, you could create your own object with class and instance variables defined in it—but how do you work with those variables? Easy! Class and instance variables are used in largely the same manner as the local variables you learned about yesterday. You can use them in expressions, assign values to them in statements, and the like. You just refer to them slightly differently than you refer to regular variables in your code.

Getting Values

To get to the value of an instance variable, you use dot notation. With dot notation, an instance or class variable name has two parts: a reference to an object or class on the left side of the dot and a variable on the right side of the dot.

Dot notation ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.