Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 111

Defining Instance and Class Variables

Оглавление

Variables that are not local variables are defined either as instance variables or as class variables. An instance variable, often called a field, is a value defined within a specific instance of an object. Let's say we have a Person class with an instance variable name of type String. Each instance of the class would have its own value for name, such as Elysia or Sarah. Two instances could have the same value for name, but changing the value for one does not modify the other.

On the other hand, a class variable is one that is defined on the class level and shared among all instances of the class. It can even be publicly accessible to classes outside the class and doesn't require an instance to use. In our previous Person example, a shared class variable could be used to represent the list of people at the zoo today. You can tell a variable is a class variable because it has the keyword static before it. You learn about this in Chapter 5. For now, just know that a variable is a class variable if it has the static keyword in its declaration.

Instance and class variables do not require you to initialize them. As soon as you declare these variables, they are given a default value. The compiler doesn't know what value to use and so wants the simplest value it can give the type: null for an object, zero for the numeric types, and false for a boolean. You don't need to know the default value for char, but in case you are curious, it is '\u0000' (NUL).

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх