Java Reference
In-Depth Information
In Java, every object belongs to some class and can be created from the class definition only. Consider the
following (partial) definition of the class
Book
:
public class Book {
private static double Discount = 0.25; //class variable
private static int MinBooks = 5; //class variable
private String author; // instance variable
private String title; // instance variable
private double price; // instance variable
private int pages; // instance variable
private char binding; // instance variable
private boolean inStock; // instance variable
// methods to manipulate book data go here
} //end class Book
The class header (the first line) consists of the following:
access modifier
;
public
is used in the example and will be used for most of our
classes. Essentially it means that the class is available for use by any other class; it can also be
extended
to create subclasses. Other access modifiers are
abstract
and
final
; we won't deal
with those in this topic.
•
An optional
class
.
•
The keyword
Book
is used in the example.
•
A user identifier for the name of the class;
The braces enclose the
body
of the class. In general, the body will include the declaration of the following:
•
Static variables (class variables); there will be one copy for the entire class—all objects will
share that one copy. A class variable is declared using the word
static
. If we omit the word
static
, the variable is
instance
.
•
Non-static variables (instance variables); each object created will have its own copy. It's the
instance variables that comprise the data for an object.
•
Static methods (class methods); these are loaded once when the class is loaded and can be
used without creating any objects. It makes no sense for a static method to access non-static
variables (which belong to objects), so Java forbids it.
•
Non-static methods (instance methods); these can be used
only
via an object created from the
class. It's the non-static methods that manipulate the data (the non-static fields) in objects.
String
class is predefined in Java. If
word
is
String
(a
String
object, to be precise) and
we write
word.toLowerCase()
, we are asking that the instance method
toLowerCase
of the
String
class be applied to the
String
object,
word
. This method converts uppercase letters to
lowercase in the (
String
) object used to invoke it.
•
The
in
is a
Scanner
object (created when we say
new Scanner...
), the expression
in.nextInt()
applies the instance method
nextInt
to the object
in
; here, it reads the next
integer from the input stream associated with
in
.
In the
Book
class, we declare two class variables (
Discount
and
MinBooks
, declared with
static
) and six instance
variables; they are
instance
by default (the word
static
is omitted).
•
Similarly, if
Search WWH ::
Custom Search