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.add(1, 3);

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

	Stack<Integer> stack = new Stack<Integer>();

	numbers = stack;

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

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

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

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.