Java basics review
Java types are strong, explicit, and checked both statically and dynamically. There are two kinds of types: primitives (bool, char, int, etc.) and classes.
Parameters are always passed by value, but all values except primitives have reference semantics (i.e., they behave like pointers).
public class Foo { // Implicitly extends (inherits) Object public int i; // Instance field member // Instance member function public String toString() { return Integer.toString(i); } // Static (classwide) member function private static void increment(int i, Foo f) { i++; f.i++; } public static void main(String[] args) { int x = 0; // Primitive integer on "stack" Foo y; // Reference to instance of class Foo y = new Foo(); // Now points to an actual instance y.i = 0; increment(x, y); // Will print "x=0, y=1" System.out.println("x=" + x + ", y=" + y); } } Other notable points:
- Some functions are instance functions, and some are static functions. Instance functions apply to instances; static functions apply to a class.
- All functions must live inside a class. In C++, the main() and incrementBoth() functions could be "free-floating", but here they are Foo static members. It's common to use the main() member of a class as its test driver.
- Unlike C++, access specifiers must be repeated for every field.
- In C++, there is a distinction between the declaration of a class (in the header file) and the implementation (typically in the .cpp file). Java methods are all written inline.
- All Java instance methods are "virtual", so there is no need for a virtual keyword.