This is for C++ programmers who need to know enough Java to understand Java examples they may encounter elsewhere.
All Java classes implicitly specialize Java's Object class. This makes it easy to create heterogeneous containers such as stacks, because we can generically refer to the items stored in the stack as objects:
class Stack
{
private int MAX = 100;
priave int size = 0;
private Object[] items = new
Object[MAX];
public void push(Object x) { if (size
< 100) items[size++] = x; }
public Object pop() throws Exception
{
if (size <= 0) throw new
Exception("Stack empty");
return items[--size];
}
// etc.
}
Of course clients must down cast items popped off the stack:
Pancake breakfast = (Pancake)PancakeStack.pop();
In addition, we can put useful operations in the Object base class that we want all objects to inherit. For example, Java's Object class includes the methods clone(), getClass(), and toString(). Java's Object base class is comparable to MFC's CObject base class.
Unlike C++, each member of a Java class must be declared public, protected, or private. Unfortunately, specifying the access of every single member gets to be quite tiring. If we forget to specify the access of a member, then the default is package scope, which means the member is visible to member functions in other classes defined in the same package.
By default, all Java member functions are virtual functions. In other words, selecting the variant of an overloaded member function is done dynamically. If we don't want a function to be virtual, then we must explicitly declare it to be non-virtual by writing the reserved word "final" in front of the function's declaration:
class MathTools
{
final public double sin(double x) { ...
}
// etc.
}
Java variables don't hold objects, instead, they hold references to heap-based objects. (A reference is a pointer that automatically dereferences itself.) For example, the declaration:
Animal x;
does not create any object, x is merely a variable that can hold a reference to an object. Of course we can assign a reference to any instance of a class that extends the Animal class, and the up cast will be performed automatically:
x = new Fish();
The analogous situation in C++ would be:
Animal& x = Fish();