Declaring Member Variables
Member variables in a class are also called fields
or instance variables
. The member variables are used to keep the state of the created object. Member variable are declared in the same way as normal variables, the same rules and conventions apply.
Field declaration are composed of three components, in order:
- Zero, or more modifiers, such as
public
orprivate
access modifier. - The field's type
- The field's name
Example
Here is a sample Message
class from a chat application. The member variables are id
, author
, createdAt
, channelId
, and text
. Notice we had to import the Date
class.
import java.util.Date;
public class Message {
String id;
String author;
Date createdAt;
String channelId;
String text;
}
Here is another example of how we could model a User
class in our chat application.
public class User {
String id;
String email;
String nickname;
String profilePictureUrl;
}
And a model Room
class for the chat application could be represented as follows:
public class Room {
String channelID;
String[] owners;
String[] members;
String title;
}
Notice in the Room
class, owners
is an array of Strings. The members
field is also an array of Strings.
Controlling Access to Member Variables
Access level modifiers determine whether other classes can use use a particular field or method of a class.
Class Fields Access Modifiers
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |
Example Access Modifiers
public
modifier
public class User {
public String profilePictureUrl;
}
The profilePictureUrl
field variable will be accessible from within a class
, package
, subclass
and the world
.
protected
modifier
public class User {
protected String profilePictureUrl;
}
With the protected
keyword, the profilePictureUrl
field is accesible from the class
, package
, subclass
but not the world
.
default
, no modifier
public class User {
String profilePictureUrl;
}
With no modifier, the field is a assigned a default
modifier. The field is accesbile from the class
and package
, but not from the subclass
and the world
.
private
modifier
public class User {
private String profilePictureUrl;
}
The field is only accesbile from within the class
and not accesible anywhere else.