The Java Programming Language, 4th Edition
by Ken Arnold, James Gosling and David Holmes (2005)
Table of Contents
Source Code
Classes and Objects
In Java, programmers must explicitly create an object. For example, in C++, Body mercury;
will create an object with default values, but in Java, it is just a declaration; mercury
is a reference to an object of type Body
.
Exercises
Exercise 2.1: Write a simple
Vehicle
class that has fields for (at least) current speed, current direction in degrees, and owner name.
class Vehicle {
public float speed;
public int degree;
public String owner;
}
Exercise 2.2: Write a
LinkedList
class that has a field of typeObject
and a reference to the nextLinkedList
element in the list.
class LinkedList {
public Object obj;
public LinkedList next;
}
Exercise 2.3: Add a static field to your
Vehicle
class to hold the next vehicle identification number, and a non-static field to the Vehicle class to hold each car’s ID number.
class Vehicle {
public long ID;
public float speed;
public int degree;
public String owner;
public static long nextID = 0;
}