Java Reference
In-Depth Information
Java lets you declare two types of fields for a class:
Class fields
Instance fields
Class fields are also known as class variables. Instance fields are also known as instance variables. In the above
snippet of code, name and gender are two instance variables of the Human class. Java has a different way to declare class
variables. All class variables must be declared using the static keyword as a modifier. The declaration of the Human
class in Listing 6-1 adds a count class variable.
Listing 6-1. Declaration of a Human Class with One Class Variable and Two Instance Variables
// Human.java
package com.jdojo.cls;
class Human {
String name; // An instance variable
String gender; // An instance variable
static long count; // A class variable because of the static modifier
}
Tip
a class variable is also known as a static variable. an instance variable is also known as a non-static variable.
Creating Instances of a Class
The following is the general syntax to create an instance of a class:
new <<Call to Class Constructor>>;
The new operator is followed by a call to the constructor of the class whose instance is being created. The new
operator creates an instance of a class by allocating the memory on heap. The following statement creates an instance
of the Human class:
new Human();
Here, Human() is a call to the constructor of the Human class. Did you add any constructor to your Human class? No.
You have not added any constructor to your Human class. You have added only three fields to it. How can you use a
constructor for a class that you have not added? When you do not add a constructor to a class, the Java compiler adds
one for you. The constructor that is added by the Java compiler is called a default constructor. The default constructor
accepts no arguments. The name of the constructor of a class is the same as the class name. I will discuss constructors
in detail later in this chapter.
What happens when an instance of a class is created? The new operator allocates memory for each instance field
of the class. Recall that class variables are not allocated memory when an instance of the class is created. Figure 6-1
depicts an instance of the Human class in memory.
 
 
Search WWH ::




Custom Search