[ Team LiB ] 6.5 Completing the Type

[ Team LiB ] 6.6 Assigning, Passing, and Casting Reference Values Reference values, like primitive values, can be assigned, cast, and passed as arguments. For values of the primitive data types and reference types, conversions can occur during . assignment . parameter passing . explicit casting The rule of thumb for the primitive data types is that widening conversions are permitted, but narrowing conversions require an explicit cast. The rule of thumb for reference values is that conversions up the type hierarchy are permitted (upcasting), but conversions down the hierarchy require explicit casting (downcasting). In other words, conversions that are from a subtype to its supertypes are allowed, other conversions require an explicit cast or are illegal. There is no notion of promotion for reference values. Reference Value Assignment Conversions Reference value assignments are generally permitted up the type hierarchy, with implicit conversion of the source reference value to that of the destination reference type. Example 6.11 Assigning and Passing Reference Values interface IStack { /* From Example 6.9 */ } interface ISafeStack extends IStack { /* From Example 6.9 */ } class StackImpl implements IStack { /* From Example 6.9 */ } class SafeStackImpl extends StackImpl implements ISafeStack { /* From Example 6.9 */ } public class ReferenceConversion { public static void main(String[] args) { // Reference declarations Object objRef; StackImpl stackRef; SafeStackImpl safeStackRef; IStack iStackRef; ISafeStack iSafeStackRef; // SourceType is a class type safeStackRef = new SafeStackImpl(10); objRef = safeStackRef;// (1) Always possible stackRef = safeStackRef;// (2) Subclass to superclass assignment iStackRef = stackRef; // (3) StackImpl implements IStack iSafeStackRef = safeStackRef;// (4) SafeStackImpl implements ISafeStack // SourceType is an interface type objRef = iStackRef; // (5) Always possible iStackRef = iSafeStackRef; // (6) Sub- to super-interface assignment // SourceType is an array type. Object[] objArray = new Object[3]; StackImpl[] stackArray = new StackImpl[3]; SafeStackImpl[] safeStackArray = new SafeStackImpl[5]; Page 327
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check Actions tomcat hosting services

Comments are closed.