0% found this document useful (0 votes)
38 views51 pages

Interfaces and Inner Classes

Uploaded by

mahadfarrukh8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views51 pages

Interfaces and Inner Classes

Uploaded by

mahadfarrukh8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CP213: Object-Oriented Programming

Interface and Inner Classes


Dr. Zia Ud Din
Modified by Dr. Zara Hamid
Lecture Outline
 Interfaces
 Inner Classes
 Anonymous Classes

Zia Ud Din CP213: Object-Oriented Programming 2


Lecture Outline
 Interfaces
 Inner Classes
 Anonymous Classes

Zia Ud Din CP213: Object-Oriented Programming 3


Interfaces
 Interface is a type that can be satisfied by any class that
implements the interface
 Declaration syntax is similar but the word interface is
used in place of class
 It specifies a set of methods that any class that
implements the interface must have
 It contains method headings and constant definitions only
 It contains no instance variables nor any complete method
definitions

Zia Ud Din CP213: Object-Oriented Programming 4


Interfaces…
 Java's way of approximating multiple inheritance is through
interfaces
 An interface and all of its method headings must be
declared public
 When a class implements an interface, it must make all the
methods in the interface public
 Because an interface is a type, a method may be written
with a parameter of an interface type
◼ That parameter will accept as an argument any class that
implements the interface

Zia Ud Din CP213: Object-Oriented Programming 5


Interfaces…
 A class can implement more than one interfaces. Each is
listed, separated by commas
 The class must implement all the method headings listed in
the definition(s) of the interface(s)

Zia Ud Din CP213: Object-Oriented Programming 6


The Ordered Interface

Zia Ud Din CP213: Object-Oriented Programming 7


Implementation of an Interface

Zia Ud Din CP213: Object-Oriented Programming 8


Implementation of an Interface

Zia Ud Din CP213: Object-Oriented Programming 9


Derived Interfaces
 Like classes, an interface may be derived from a base
interface
◼ This is called extending the interface
◼ The derived interface must include the phrase
extends BaseInterfaceName

 A concrete class that implements a derived interface must


have definitions for any methods in the derived interface
as well as any methods in the base interface

Zia Ud Din CP213: Object-Oriented Programming 10


Extending an Interface

Zia Ud Din CP213: Object-Oriented Programming 11


Interface Semantics
 Note: Interface semantics are not enforced by compiler or
runtime system
 Required semantics are normally added to the
documentation
◼ It then becomes the responsibility of each programmer
implementing the interface to follow the semantics

Zia Ud Din CP213: Object-Oriented Programming 12


The Comparable Interface
 Chapter 6 discussed the Selection Sort algorithm, and examined a
method for sorting a partially filled array of type double into
increasing order
 See the next few slides copied from Chapter 6…

Zia Ud Din CP213: Object-Oriented Programming 13


Selection Sort
 The algorithm’s first iteration selects the smallest element value and
swaps it with the first element’s value.
 The second iteration selects the second-smallest element value and
swaps it with the second element’s value.
 The algorithm continues until the last iteration selects the second-
largest element and swaps it with the second-to-last element’s value,
leaving the largest value in the last element.
 After the ith iteration, the smallest i values will be sorted into
increasing order in the first i array elements.

Zia Ud Din CP213: Object-Oriented Programming 14


Selection Sort (Part 1 of 2)

Zia Ud Din CP213: Object-Oriented Programming 15


Selection Sort (Part 2 of 2)

Zia Ud Din CP213: Object-Oriented Programming 16


SelectionSort Class (Part 1 of 2)
public class SelectionSort {
public static void sort(double[] a) {
int index, indexOfNextSmallest;
for (index = 0; index < a.length - 1; index++) {
indexOfNextSmallest = indexOfSmallest(index, a);
interchange(index, indexOfNextSmallest, a);
}
}

private static int indexOfSmallest(int startIndex, double[] a) {


double min = a[startIndex];
int indexOfMin = startIndex;
int index;
for (index = startIndex + 1; index < a.length; index++)
if (a[index] < min) {
min = a[index];
indexOfMin = index;
}
return indexOfMin;
}

Zia Ud Din CP213: Object-Oriented Programming 17


SelectionSort Class (Part 2 of 2)
private static void interchange(int i, int j, double[] a) {
double temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public static void main(String[] args) {


double[] a = {8,6,11,17,3,15,5,19,28,12};
System.out.println("Initial array: ");
for (double element : a)
System.out.print(element + ", ");
sort(a);
System.out.println("\nSorted array: ");
for (double element : a)
System.out.print(element + ", ");
}
}

Zia Ud Din CP213: Object-Oriented Programming 18


Selection Sort using Comparable Interface
 This code could be modified to sort into decreasing order, or to sort
integers or strings instead
◼ Each of these methods would be essentially the same, but making each
modification would be a nuisance
◼ The only difference would be the types of values being sorted, and the
definition of the ordering
 Using the Comparable interface could provide a single sorting
method that covers all these cases

Zia Ud Din CP213: Object-Oriented Programming 19


The Comparable Interface
 The Comparable interface is in the java.lang package
 It has only the following method heading that must be
implemented:
public int compareTo(Object other);
 The method compareTo must return
◼ A negative number if the calling object "comes before" the
parameter other
◼ A zero if the calling object "equals" the parameter other
◼ A positive number if the calling object "comes after" the
parameter other

Zia Ud Din CP213: Object-Oriented Programming 20


The Comparable Interface Semantics

 Almost any reasonable notions of "comes before" and


"comes after" are acceptable
 The "equals" of the compareTo method semantics should
coincide with the equals method if possible, but this is not
absolutely required

Zia Ud Din CP213: Object-Oriented Programming 21


Comparable – an interface in Java

– We cannot create objects of an interface type


– We are allowed to create objects of a type that implements the
interface, and then treat them as though they were an interface
type

Bad:
Comparable c = new Comparable(); // error
Good:
Comparable c; // okay
Comparable – an interface in Java
MyClass m = new MyClass(); // MyClass implements Comparable

c = m; // legal – can manipulate c as though it is an object of type


Comparable, even though it is illegal to create such an object

• 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

Zia Ud Din CP213: Object-Oriented Programming 24


GeneralizedSelectionSort Class (Part 1 of 4)
public class GeneralizedSelectionSort {
public static void sort(Comparable[] a) {
int index, indexOfNextSmallest;
for (index = 0; index < a.length - 1; index++) {
indexOfNextSmallest = indexOfSmallest(index, a);
interchange(index, indexOfNextSmallest, a);
}
}

private static int indexOfSmallest(int startIndex, Comparable[] a) {


Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for (index = startIndex + 1; index < a.length; index++)
if (a[index].compareTo(min) < 0) {
min = a[index];
indexOfMin = index;
}
return indexOfMin;
}

Zia Ud Din CP213: Object-Oriented Programming 25


GeneralizedSelectionSort Class (Part 2 of 4)

private static void interchange(int i, int j, Comparable[] a) {


Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}

Zia Ud Din CP213: Object-Oriented Programming 26


GeneralizedSelectionSort Class (Part 3 of 4)
public static void main(String[] args) {
Double[] a = {8.0,6.2,11.5,17.6,3.0,15.4,5.2,19.8,28.4,12.9};
System.out.println("Initial array: ");
for (Double element : a)
System.out.print(element + ", ");
sort(a);
System.out.println("\nSorted array: ");
for (Double element : a)
System.out.print(element + ", ");

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 + ", ");
}

Zia Ud Din CP213: Object-Oriented Programming 27


GeneralizedSelectionSort Class (Part 4 of 4)

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,

Zia Ud Din CP213: Object-Oriented Programming 28


Defined Constants in Interfaces
 An interface can contain defined constants in addition to or
instead of method headings
◼ Any variables defined in an interface must be public, static, and
final
◼ Because this is understood, Java allows these modifiers to be
omitted
 Any class that implements the interface has access to
these defined constants

Zia Ud Din CP213: Object-Oriented Programming 29


The Cloneable Interface
 The Cloneable interface is an unusual example of a Java
interface
◼ It does not contain method headings or defined constants (such
interfaces are called marker interfaces)
◼ It is used to indicate how the method clone (inherited from the
Object class) should be used and redefined

Zia Ud Din CP213: Object-Oriented Programming 30


The Cloneable Interface
 The method Object.clone() does a bit-by-bit copy of the
object's data in storage
 If the data is all primitive type data or data of immutable
class types, then this is adequate
 If the data in the object to be cloned includes instance
variables whose type is a mutable class, then the simple
implementation of clone would cause a privacy leak

Zia Ud Din CP213: Object-Oriented Programming 31


The Cloneable Interface…
 When implementing the Cloneable interface for a class
with mutable class types:
◼ First invoke the clone method of the base class Object (or
whatever the base class is)
◼ Then reset the values of any new instance variables whose types
are mutable class types
 This is done by making copies of the instance variables by invoking their
clone methods
 Note that this will work properly only if the Cloneable
interface is implemented properly for the classes to which
the instance variables belong

Zia Ud Din CP213: Object-Oriented Programming 32


Implementation of the Method clone

Zia Ud Din CP213: Object-Oriented Programming 33


Some Other Commonly Used Interfaces
 Runnable:
◼ The Runnable interface is used to define a task that can be
executed concurrently.
◼ It contains a single method, run(), which must be implemented to
define the code that the task will execute.
 Serializable:
◼ The Serializable interface is an interface used to indicate that a
class can be serialized.
◼ Serialization is the process of converting an object into a stream
of bytes to store or transmit it to memory, a database, or a file.

Zia Ud Din CP213: Object-Oriented Programming 34


Lecture Outline
 Interfaces
 Inner Classes
 Anonymous Classes

Zia Ud Din CP213: Object-Oriented Programming 35


Inner Classes
 Inner classes are classes defined within other classes
 An inner class definition is a member of the outer class in
the same way that the instance variables and methods of
the outer class are members
 There are two main advantages to inner classes
◼ They can make the outer class more self-contained since they are
defined inside a class
◼ Both of their methods have access to each other's private
methods and instance variables

Zia Ud Din CP213: Object-Oriented Programming 36


Simple Uses of Inner Classes

• Inner classes are classes defined within other classes


– The class that includes the inner class is called the outer
class
– There is no particular location where the definition of the inner
class (or classes) must be place within the outer class
– Placing it first or last, however, will guarantee that it is easy to
find
Simple Uses of Inner Classes

• An inner class definition is a member of the outer


class in the same way that the instance variables and
methods of the outer class are members
– An inner class is local to the outer class definition
– The name of an inner class may be reused for
something else outside the outer class definition
– If the inner class is private, then the inner class cannot be
accessed by name outside the definition of the outer class
Inner Classes…
 Using an inner class as a helping class is a useful applications
◼ Should be marked private in that case
 Inner classes can be static or non-static

Zia Ud Din CP213: Object-Oriented Programming 39


Tip: Inner and Outer Classes Have Access
to Each Other's Private Members

• Within the definition of a method of an inner class:


– It is legal to reference a private instance variable of the outer class
– It is legal to invoke a private method of the outer class
• Within the definition of a method of the outer class
– It is legal to reference a private instance variable of the inner class on an object of the
inner class
– It is legal to invoke a (nonstatic) method of the inner class as long as an object of the
inner class is used as a calling object
• Within the definition of the inner or outer classes, the modifiers public
and private are equivalent
The .class File for an Inner
Class

• Compiling any class in Java produces a .class


file named ClassName.class
• Compiling a class with one (or more) inner classes causes both (or
more) classes to be compiled, and produces two (or more) .class
files
– Such as ClassName.class and
ClassName$InnerClassName.class
A Non-Static Inner Class
public c l a s s OuterClass1 {
private i n t outerVar;
public void outerMethod() {
InnerClass inner = new InnerClass(); Output:
inner.innerMethod(); Value of outerVar is 10
}

public c l a s s InnerClass {
public void innerMethod() {
outerVar = 10;
System.out.println("Value of outerVar i s " + outerVar);
}
}

public s t a t i c void main(String[] args) {


OuterClass outer = new OuterClass();
outer.outerMethod();
}
}

Zia Ud Din CP213: Object-Oriented Programming 42


A Non-Static Inner Class…
 A non-static inner class is associated with an instance of the outer class.
public c l a s s OuterClass2 {

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);
}
}

public s t a t i c void main(String[] args) {


OuterClass2 outer = new OuterClass2();
outer.outerMethod();

OuterClass2.InnerClass inner = outer.new InnerClass();


inner.innerMethod();
}
}

Zia Ud Din CP213: Object-Oriented Programming 43


A Static Inner Class
 A static inner class is not associated with a specific instance of the
outer class.
 Can access only the static members of the outer class.
public c l a s s OuterClass3 {
private i n t outerVar;
public void outerMethod() {
InnerClass inner = new InnerClass();
inner.innerMethod(); Output:
}
Inside static InnerClass
public s t a t i c c l a s s InnerClass {
public void innerMethod() {
System.out.println("Inside static InnerClass");
// System.out.println(outerVar); // Error
}
}

public s t a t i c void main(String[] args) {


OuterClass3.InnerClass inner = new OuterClass3.InnerClass();
inner.innerMethod();
}
}

Zia Ud Din CP213: Object-Oriented Programming 44


Nesting Inner Classes

• It is legal to nest inner classes within inner


classes
– The rules are the same as before, but the names get
longer
– Given class A, which has public inner class B, which
has public inner class C, then the following is valid:
A aObject = new A();
A.B bObject = aObject.new B();
A.B.C cObject = bObject.new C();
Inner Classes and Inheritance

• Given an OuterClass that has an


InnerClass
– Any DerivedClass of OuterClass will
automatically have InnerClass as an inner class
– In this case, the DerivedClass cannot override the
InnerClass
• An outer class can be a derived class
• An inner class can be a derived class also
Lecture Outline
 Interfaces
 Inner Classes
 Anonymous Classes

Zia Ud Din CP213: Object-Oriented Programming 47


Anonymous Classes
 Anonymous classes are a way to create objects without
explicitly defining a class.
 They are defined and instantiated in a single expression,
typically used for quick and simple implementations.
 Useful for implementing interfaces or extending classes
with only a few methods.
 Ideal for event handling in GUI applications, where you
need a one-time-use class.

Zia Ud Din CP213: Object-Oriented Programming 48


Anonymous Classes Example (Part 1 of 2)
public interface NumberCarrier {
public void setNumber(int value);
public int getNumber();
}

public class AnonymousClassDemo {


public static void main(String[] args) {
NumberCarrier anObject = new NumberCarrier() {
private int number;
public void setNumber(int value) {
number = value;
}
public int getNumber() {
return number;
}
};

AnonymousClassDemo class continues on the next slide

Zia Ud Din CP213: Object-Oriented Programming 49


Anonymous Classes Example (Part 2 of 2)
NumberCarrier anotherObject = new NumberCarrier() {
private int number;
public void setNumber(int value) {
number = 2*value;
}
public int getNumber() {
return number;
}
}; Output:
anObject.setNumber(10); 10
anotherObject.setNumber(10); 20
showNumber(anObject);
showNumber(anotherObject);
}
public static void showNumber(NumberCarrier o) {
System.out.println(o.getNumber());
}
}

Zia Ud Din CP213: Object-Oriented Programming 50


Summary
 We discussed the following topics:
◼ Interfaces
◼ Inner Classes
◼ Anonymous Classes

Zia Ud Din CP213: Object-Oriented Programming 51

You might also like