In Java, there is no good support for singular objects as described in Chapter 2. In most cases, objects are instances of classes so to create objects like BirgersCar and LizasCar we use class Car which may be defined as follows:
class Car { Car(int lN, int kW) { licenseNumber = lN; kerbWeight = kW; } int licenseNumber ; int kerbWeight; int payload; void addPassenger(){ payload = payload + 80; } }
Explain class Car, the constructor, introduce main and show how to create instances.
In Java, a singular object is called an anonymous class and BirgersCar may be written as an anonymous class.
You may skip this section during a first reading, since we don't use anonymous classes until later in this part on Java.
BirgersCar may be written as an anonymous class as shown in the following example:
Object BirgersCar = new Object(){ integer licenseNumber = 10203040; integer kerbWeight = 1500; integer payLoad = 0; void addPassenger(){ payLoad = payLoad + 80; } }
However, anonymous classes are is not a good way to define singular objects like BirgersCar since there is a lot of restrictions on these. You may e.g. not invoke a method as in BrigersCar.addPassenger();