Interfaces and Inner Classes
Interfaces and Inner Classes
Bad:
Comparable c = new Comparable(); // error
Good:
Comparable c; // okay
Comparable – an interface in Java
MyClass m = new MyClass(); // MyClass implements Comparable
• Works not only with Comparable, but also with any interface
• can declare methods which take objects as parameters of type
Comparable
• can declare sorting methods where the input is an array of
type Comparable
Comparable[] c = new Comparable[5]; // This does not create any
new objects – it only creates space for the array
Using the Comparable Interface
The following example reworks the SelectionSort class
from Chapter 6
The new version, GeneralizedSelectionSort, includes a
method that can sort any partially filled array whose base
type implements the Comparable interface
◼ It contains appropriate indexOfSmallest and interchange
methods as well
Note: Both the Double and String classes implement the
Comparable interface
◼ Interfaces apply to classes only
◼ A primitive type (e.g., double) cannot implement an interface
String[] s = {"Java", "Python", "C", "C++", "SmallTalk", "Fortran", "Cobol", "Scheme", "Prolog"};
System.out.println("\n\nInitial array: ");
for (String element : s)
System.out.print(element + ", ");
sort(s);
System.out.println("\nSorted array: ");
for (String element : s)
System.out.print(element + ", ");
}
Output:
Initial array:
8.0, 6.2, 11.5, 17.6, 3.0, 15.4, 5.2, 19.8, 28.4, 12.9,
Sorted array:
3.0, 5.2, 6.2, 8.0, 11.5, 12.9, 15.4, 17.6, 19.8, 28.4,
Initial array:
Java, Python, C, C++, SmallTalk, Fortran, Cobol, Scheme, Prolog, Sorted array:
C, C++, Cobol, Fortran, Java, Prolog, Python, Scheme, SmallTalk,
public c l a s s InnerClass {
public void innerMethod() {
outerVar = 10;
System.out.println("Value of outerVar i s " + outerVar);
}
}
private i n t outerVar;
public void outerMethod() {
InnerClass inner = new InnerClass();
inner.innerMethod(); Output:
}
Value of outerVar is 10
public c l a s s InnerClass {
Value of outerVar is 10
public void innerMethod() {
outerVar = 10;
System.out.println("Value of outerVar i s " + outerVar);
}
}