A Java Class

Visually, the Java syntax closely resembles C++. One key difference, however, is the absence of header (or interface) files. Typically, there's a 1:1 ratio between a class and a file.

Here is the equivalent class for Java:

  1. package com.crowleyworks.futilefishing.model;
  2.  
  3. public class FishingSpot {
  4.  
  5. public FishingSpot() {
  6. this.name = "undefined";
  7. this.comments = "";
  8. }
  9.  
  10. public FishingSpot(String name, double latitude, double longitude) {
  11. this.name = name;
  12. this.latitude = latitude;
  13. this.longitude = longitude;
  14. this.comments = "";
  15. }
  16.  
  17. private String name;
  18. public String getName() { return name; }
  19. public void setName(String name) { this.name = name; }
  20.  
  21. private double latitude;
  22. public double getLatitude() { return latitude; }
  23. public void setLatitude(double latitude) { this.latitude = latitude; }
  24.  
  25. private double longitude;
  26. public double getLongitude() { return longitude; }
  27. public void setLongitude(double longitude) { this.longitude = longitude; }
  28.  
  29. private String comments;
  30. public String getComments() { return comments; }
  31. public void setComments(String comments) { this.comments = comments; }
  32.  
  33. @Override
  34. public String toString() {
  35. return name + " Latitude: " + latitude +
  36. " Longitude: " + longitude + " Comments: " +
  37. ((comments==null || comments.length()<1) ? "none" : comments);
  38. }
  39. }

Notes:

  • Line 1: The package namespace declaration. This, combined with the class name, ensures that two classes with the same name don't collide.
  • Line 3: The class declaration.
  • Lines 5-8: The definition AND implementation of a zero-parameter constructor.
  • Lines 10-15: A constructor that takes three parameters. Note that parameters and class variable names match. This is not required, but it's a Java convention.
  • Lines 17-31: The definition of the class properties and the associated getters / setters. The formatting is not a Java convention, but I think it increases the readability of the code
  • Lines 33-38: This method describes how the class should be displayed as a string. (This is the same as the Objective-C description() method.
  • Line 39: The end of the class declaration.