Sunday, October 18, 2009

Section 13.3. Substitution Principle







13.3. Substitution Principle

As specified in Java Generics and Collections, the Substitution Principle allows subtypes to be used where their supertype is parameterized:

  • A variable of a given type may be assigned a value of any subtype of that type.

  • A method with a parameter of a given type may be invoked with an argument of any subtype of that type.

Byte, Short, Integer, Long, Float, Double, BigInteger, and BigDecimal are all subtypes of class Number.

	// List declared with generic Number type
List<Number> nList = new ArrayList<Number>( );
nList.add((byte)27); // Byte (Autoboxing)
nList.add((short)30000); // Short
nList.add(1234567890); // Integer
nList.add((long)2e62); // Long
nList.add((float)3.4); // Float
nList.add(4000.8); // Double
nList.add(new BigInteger("9223372036854775810"));
nList.add(new BigDecimal("2.1e309"));

// Print Number's subtype values from the list
for( Number n : nList )
System.out.println(n);









No comments:

Post a Comment