Variables have a declared type, and each variable stores a particular value.
Every type in Java is one of the following.
Every value in Java is one of the following.
Subtype relationship between types: by substitution principle, a
variable of a subtype can be used in place of its supertype.
Rules are that
Employee ^ | Manager ^ | VicePresidentIn this scenario,
EventListener ^ | MouseListener ^ | MouseInputListenerIn this scenario,
EventListener
^
|
MouseListener <-- MouseAdapater
^ ^
| |
MouseInputListener <-- MouseInputAdapter
^
|
BasicSliderUI.TrackListener
For example, the BasicSliderUI.TrackListener class is a
subtype of the EventListener interface.
By above, the type Rectangle[] is a subtype of Shape[]. But this means we can do the following:
Rectangle[] ra = new Rectangle[10]; ra[0] = new Rectangle(1,2,3,4); Shape[] sa = ra; // legalBut given the declaration of sa, should it be legal syntax to do
sa[0] = new Polygon(...);Syntactically that is legal, but it would then leave the array ra referencing an object that is not of the proper type. Java handles this by having an ArrayStoreException at runtime; each underlying array knows its component type.
public enum Size { SMALL, MEDIUM, LARGE };
Technically, these are implemented in Java as classes, and in particular as subtypes of an Enum class.
Can perform runtime checks to determine more about the true type of a value.
Object x = ...
if (x instanceof Shape) { ... }
The instanceof operator allows for checks of the formal subtype relationships.
That is different from asking what the true type is of a value. That reflections is also possible using the syntax
Class c = x.getClass(); // valid for x having any non-primitive typeFormally, this is supported by Object.getClass().
Some supported methods of Object.
For all non-primitive types, the expression x == y determines whether x and y are references to the same object.
That is not necessarily the same notion as equivalence in the context of some type. For example, two distinct String instances, might represent the identical sequence of characters. The Object.equals method is used to support a syntax x.equals(y) for all non-primitive types. By default, Object.equals defines equivalence to be the same as identity
public boolean equals(Object obj) {
return this == obj;
}
however other classes are free to override this behavior to provide
better semantics for equivalence. For example, String.equals
defines equality based instances having the identical sequence of characters.
Requirements for a consistent equals method
We will look at a detailed example next time...