CSci 2101: Overview of Java subtyping

Types and subtyping

Will the following program compile? If some fragments of it do not compile, comment them out (and explain why they don't compile). If you run the program after these lines (if any) have been commented out, what will happen? Show the results of all printing. If any run-time errors occur, clearly explain where they happen and why. Then comment out the error and continue with the program.


import java.util.List;
import java.util.LinkedList;
import java.util.Stack;

/**
List<E> is an interface that extends Iterable<E>
and declares methods 
void add(int index, E item)
void remove(int index)
E get(int index)

LinkedList<E> is a class that implements List<E>

Stack<E> is another class that implements List<E>

It defines methods 
boolean empty() 
E pop()
void push(E item) 
E peek() 
 **/

public class Types {
    public static void main(String [] args) {
	List<Integer> numbers = new LinkedList<Integer>();
	
	numbers.add(0, 1);
	numbers.add(0, 2);
	numbers.remove(0);
	numbers.add(1, 3);

	System.out.println("Printing 1:");
	for (int number: numbers) {
	    System.out.println(number);
	}

	Stack<Integer> stack = new Stack<Integer>();
	stack.push(4);
	stack.push(5);
	stack.push(6);

	numbers = stack;

	System.out.println("Printing 2:");
	for (int number: numbers) {
	    System.out.println(number);
	}

	numbers.pop();
	System.out.println("numbers.get(0) = " + numbers.get(0));
	stack.pop();
	System.out.println("Printing 3:");
	for (int number: numbers) {
	    System.out.println(number);
	}

	LinkedList<Integer> anotherList = (LinkedList<Integer>) numbers;
	System.out.println("anotherList.get(0) = " + anotherList.get(0));	
	
    }
}


CSci 2101 course web site.