3.3. Java Basics

One of the most obvious and immediate differences between Objective C (and incidentally C++) and Java, is that Java does not partion classes into "declarations" (header files) and "implementations" (implementation files). All information for any Java class is contained in a single .java file.

Perhaps the best way to illustrate this is to consider the Java equivalent of the previous Objective C Example 3-1.


Example 3-3. Java class

public class Bug extends SwarmObject 
{
  int xPos, yPos;
  int worldXSize, worldYSize;
  FoodSpace foodSpace;

 public Object setX$Y (int x, int y)
  {
    xPos = x;
    yPos = y;
    return this;
  }
 public Object step()
  {
    // body of step() code
    return this;
  }
 public return_type look(direction_type d)
  {
    return_type returnval;
    // body of look() code
    return returnval;
  }
}
Complete class defintionSub classSuper classInstance Variablesdeclares method called set$Y() that takes two argumentsdeclares a method called step() takes no arguments.declares a method called look() that takes one argument of type direction_type and returns an argument of type return_type.

One important distinction to notice is that Java does not have a notion of an id or "generic" data type. All variables must be assigned a type, in the above example the foodSpace instance variable is declared as being of type FoodSpace. This is because Java is a strongly typed language. The compiler checks all types of all variables to ensure all receiver objects respond to the messages that are sent to them by the programmer. Most of the rest of the other differences between the Objective C and Java examples given, lie almost purely in deviations of syntax. Here are a few obvious ones (this list is by no means exhaustive and the reader is encouraged to consult their Java or Objective C reference manual for all the detailed syntax):