University of Toronto - Fall 2000
Department of Computer Science

Week 11 - The instanceof operator

Fails without instanceof

	class Person { . . . }

	class Student extends Person {
		private String stunum;
		public Student (String n, String b, String s) {
			super (n, b);
			this.stunum = s;
		}
		public String getStunum() {
			return stunum;
		}
	}

	import java.io.*;
	public class School {
		public static void main (String[] args) throws IOException {
			BufferedReader in = new BufferedReader(new InputStreamReader
													(System.in));

			Person[] list = new Person [...];
			// Here give values to list's element.
			// Some of them will be Students.

			// Print student numbers.
			for (int i=0; i < list.length; i++) {
				// This fails …
				System.out.println(list[i].getStunum());
		}
	}

Works using instanceof

	class Person { . . . }

	class Student extends Person {
		private String stunum;
		public Student (String n, String b, String s) {
			super (n, b);
			this.stunum = s;
		}
		public String getStunum() {
			return stunum;
		}
	}

	import java.io.*;
	public class School {
		public static void main (String[] args) throws IOException {
			BufferedReader in = new BufferedReader(new InputStreamReader
													(System.in));

			Person[] list = new Person [...];
			// Here give values to list's element.
			// Some of them will be Students.

			// Print student numbers.
			for (int i=0; i < list.length; i++) {
				if (list[i] instanceof Student) {
					System.out.println (((Student)list[i]).getStunum());
				}
			}
		}
	}