Java Reference
In-Depth Information
addresses, and so on. Java is an object-oriented programming language and thus
has some significant syntax related to OO concepts.
If you are new to object-oriented programming, be sure to read Chapter 1
of Eckel's
Thinking in Java
.
In Java, we define a
class
to represent the objects about which we want to
program. A class consists of the data and the methods to operate on that data.
When we create a new instance of some class, that instance is an object of that
type of class. Example 3.5 shows a simple class.
Example 3.5
Simple class
class
PairInt
{
// data
int i;
int j;
// constructors
PairInt() { i=0; j=0; }
PairInt(int ival, int jval) { i=ival; j=jval; }
// methods
setI(int val) { i=val; }
setJ(int val) { j=val; }
int getI() { return i; }
int getJ() { return j; }
}
Note that this class defines both data (
i
,
j
) and methods (
setI()
,
getJ()
, and so on). We put all this into a file named
PairInt.java
to match
the name of the class definition.
If some other Java code wanted to create and use a
PairInt
object, it
would create it with the
new
keyword followed by a call to a constructor
(Example 3.6).
This example shows only a snippet of code, not the entire
PairInt
class.
That class, though, would likely reside in its own source file (named for its class
name). In Java you normally create lots of files, one for each class. When it's