Java Reference
In-Depth Information
Observe that the body of the no-arg constructor consists of an empty block. When the following statement is executed,
the instance variables are set to their initial values (specified or default), and the constructor is executed. In this case,
nothing further happens.
Book b = new Book();
Be warned that when we provide a constructor, the default no-arg constructor is no longer available. If we want to
use a no-arg constructor as well, we must write it explicitly, as in the previous example. We are free, of course, to write
whatever we want in the body, including nothing.
As a final example, we provide a constructor that lets us set all the fields explicitly when an object is created. Here
it is:
public Book(String a, String t, double p, int g, char b, boolean s) {
author = a;
title = t;
price = p;
pages = g;
binding = b;
inStock = s;
}
If b is a variable of type Book , a sample call is as follows:
b = new Book("Noel Kalicharan", "DigitalMath", 29.95, 200, 'P', true);
The fields will be given the following values:
author "Noel Kalicharan"
title "DigitalMath"
price 29.95
pages 200
binding 'P'
inStock true
2.4 Data Encapsulation, Accessor, and Mutator Methods
We will use the term user class to denote a class whose methods need to access the fields and methods of another class.
When a class's field is declared public , any other class can access the field directly, by name. Consider the
following class:
public class Part {
public static int NumParts = 0; // class variable
public String name; // instance variable
public double price; // instance variable
}
Here, we define one static (or class) variable and two instance variables as public . Any user class can access the
static variable using Part.NumParts and can include statements such as this:
Part.NumParts = 25;
 
Search WWH ::




Custom Search