Previous Lecture Lecture 8 Next Lecture

Lecture 8, Wed 04/24

Interfaces, Switch Statements

Interfaces

Example implementing the comparable interface

public interface Comparable
{
	// compares two objects: x.compareTo(y) such that
	// if x == y, return 0
	// if x < y, return -1
	// if x > y, return 1
    int compareTo(Object obj);
}

int compareTo​(T o)

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

public abstract class Student extends Person implements Comparable {

// Implement the Interface’s method in the Student class
// We can compare students based on their PERM 
public int compareTo(Object o) {
    Student x = (Student) o; 
    if (studentID < x.perm) {
        return -1;
    } else if (perm > x.perm) {
        return 1;
    } else {
        return 0;
    }
}

Example Using compareTo with Student Objects

public static Student findMinStudent(Comparable[] c) {
    Student minStudent = (Student) c[0];
    
    for (int i = 1; i < c.length; i++) {
        if (c[i].compareTo(minStudent) < 0) {
            minStudent = (Student) c[i];
        }
    }
    return minStudent;
}
// in main
Student[] array = new Student[2];
array[0] = new NonResidentStudent("Richert", 21, 80498567, "Oregon");
array[1] = new DomesticStudent("Zorra", 18, 1234567, "Los Angeles");

Student minStudent = findMinStudent(array);

System.out.println(minStudent.toString());

System.out.println(array[0].compareTo(array[1]));
System.out.println(array[1].compareTo(array[0]));

Switch Statements

Example

int studentYear = 2;
String status;
switch (studentYear) { // switch block
	case 1: status = "Freshman";
		break;
	case 2: status = "Sophomore";
		break; // if this was removed, it will evaluate case 3.
	case 3: status = "Junior";
		break;
	case 4: status = "Senior";
		break;
	default: status = "Undefined";
		break;
} // end switch block
System.out.println(status);

Example with multiple values for a single case block

switch (studentYear) { // switch block
    case 1: case 2:
        status = "LowerDivision";
        break;

    case 3: case 4:
        status = "UpperDivision";
        break;
    default: status = “Undefined”;
        break;
} // end switch block
System.out.println(status);

Example using String values in switch cases

String studentYear = "junior";
String status;

switch (studentYear) { // switch block
case "freshman": case "sophomore":
        status = "LowerDivision";
        break;

case "junior": case "senior":
        status = "UpperDivision";
        break;
default: status = "Undefined";
        break;
} // end switch block
System.out.println(status);