Lec23-Interface ClassComparable Interface

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Interface Class

&
Comparable Interface
Lecture 23
Based on Slides of Dr. Norazah Yusof

1
Interface & Implements
• An interface is a classlike construct that
contains only constants variables and abstract
methods definition.
• An interface cannot contain instance variable
and solid methods.
• An interface specifies what methods will be
implemented by classes that implements an
interface.
• This is another way to design polymorphic
methods.

2
Interface
 All classes share a single root, the Object class, but there
is no single root for interfaces.
 Like a class, an interface also defines a type.
 A variable of an interface type can reference any instance
of the class that implements the interface.
 If a class extends an interface, this interface plays the
same role as a superclass. You can use an interface as a
data type and cast a variable of an interface type to its
subclass, and vice versa.

3
Interface
Interface1_2 Interface2_2

Interface1_1 Interface1 Interface2_1

Object Class1 Class2

Suppose that c is an instance of Class2. c is also an


instance of Object, Class1, Interface1, Interface1_1,
Interface1_2, Interface2_1, and Interface2_2.

4
Interface declaration
• Declaration:
public interface InterfaceName
{
/* constant declaration */
/* method declarations (without
implementations.) */
}

• Constant declarationpublic, static and final


• Methodabstract, public

5
Interface declaration
In an interface, by default all data fields are constant
variables and defined as public final static and all methods are
public abstract.
For this reason, these modifiers can be omitted, as shown
below:
public interface T1 { public interface T1 {
public static final int K = 1; Equivalent int K = 1;

public abstract void p(); void p();


} }

A constant defined in an interface can be accessed using syntax


InterfaceName.CONSTANT_NAME (e.g., T1.K).

6
Ex: Interface declaration
(constant variables)
public interface Conversionfactors
{
double inToMm = 25.3;
double ounToGram = 28.34952;
double poundToGram = 453.5924 ;
}
• Save as ConversionFactors.java

7
Ex: Interface declaration
(Abstract Methods)
public interface Conversions {
public double InToMm();
public double OunceToGram();
public double PoundToGram();
}
• Save as Conversions.java

8
Ex: Interface declaration
(variables and Methods)
public interface MyInterface {
public final int aConstant = 32;
public final double pi = 3.14159;

public void methodA(int x);


double methodB();
}

9
Implementing an Interface
 A class may extends one parent (superclass), but it
can implement none or more interfaces
 A class that implements an interface:
 Can access directly all the variables declared in
the interface
 Have to redefined all the methods declared in
the interface
 Declaration:
class SomeClass extends Parent implements SomeInterface
{ ordinary class definition body }

10
• The body of the class definition is the
same as always.
• If any of the abstract methods (in the
interface) are not defined in the class that
implements the interface, the class will
become an abstract class

11
Example 1
public interface Speakable {
public String speak();
}

public class Animal {


protected String kind;
public Animal() { };
public String toString(){
return "I am a " + kind + " and I go " +
((Speakable)this).speak();
}
}

12
Example 1
public class Cat extends Animal implements Speakable {
public Cat() {
kind ="cat"; }
public String speak() {
return "meow"; }
}

public class Cow extends Animal implements Speakable {


public Cow() {
kind ="cow"; }
public String speak(){
return "moo"; }
}

13
class Main {
public static void main(String[] args) {

Cat mycat = new Cat(); // Create a cat object


System.out.println(mycat.toString());
System.out.println(mycat.speak());

Cow mycow= new Cow(); // Create a cow object


System.out.println(mycow.toString());
System.out.println(mycow.speak());
}
}
Interface vs Abstract
• In many ways, an interface is similar to
an abstract class, but
• an abstract class can contain variables and concrete
methods as well as constants and abstract methods.
• In an interface, the data must be constants; an
abstract class can have all types of data.
• Each method in an interface has only a signature
without implementation; an abstract class can have
concrete methods.

15
Interface vs Abstract
Variables Constructors Methods

Abstract No Constructors are invoked No restrictions.


class restrictions by subclasses through
constructor chaining. An
abstract class cannot be
instantiated using the new
operator.
Interface All No constructors. An All methods
variables interface cannot be must be public
must be instantiated using the new abstract
public static operator. instance
final methods

16
Comparable Interface
// This interface is defined in
// java.lang package
package java.lang;

public interface Comparable {


public int compareTo(Object o);
}

Determine the order of given object with the specified object o,


and return a negative integer if this object is less than,
return a zero if this object is equal,
return a positive integer if this object is greater than,
the specified object o.

17
String and Date Classes
Many classes (e.g., String and Date) in the Java library
implement Comparable to define a natural order for the objects.
If you examine the source code of these classes, you will see the
keyword implements used in the classes, as shown below:

public class String extends Object public class Date extends Object
implements Comparable { implements Comparable {
// class body omitted // class body omitted
} }

new String() instanceof String


new String() instanceof Comparable
new java.util.Date() instanceof java.util.Date
new java.util.Date() instanceof Comparable

18
Generic max Method
// Max.java: Find a maximum object // Max.java: Find a maximum object
public class Max { public class Max {
/** Return the maximum of two objects */ /** Return the maximum of two objects */
public static Comparable max public static Object max
(Comparable o1, Comparable o2) { (Object o1, Object o2) {
if (o1.compareTo(o2) > 0) if (((Comparable)o1).compareTo(o2) > 0)
return o1; return o1;
else else
return o2; return o2;
} }
} }

(a) (b)

String s1 = "abcdef"; Date d1 = new Date();


String s2 = "abcdee"; Date d2 = new Date();
String s3 = (String)Max.max(s1, s2); Date d3 = (Date)Max.max(d1, d2);

The return value from the max method is of the Comparable type.
So, you need to cast it to String or Date explicitly.

19
Declaring Classes to Implement Comparable
Notation: GeometricObject «interface»
The interface name and the - java.lang.Comparable
method names are italicized.
The dashed lines and hollow Rectangle +compareTo(o: Object): int
triangles are used to point to -
the interface.
ComparableRectangle
-

You cannot use the max method to find the larger of two instances of Rectangle, because
Rectangle does not implement Comparable. However, you can declare a new rectangle
class that implements Comparable. The instances of this new class are comparable. Let
this new class be named ComparableRectangle.
ComparableRectangle rectangle1 = new ComparableRectangle(4, 5);
ComparableRectangle rectangle2 = new ComparableRectangle(3, 6);
System.out.println(Max.max(rectangle1, rectangle2));

20
Example of an Interface
// This interface is defined in
// java.lang package
package java.lang;

public interface Comparable {


public int compareTo(Object o);
}
Determine the order of given object with the specified object o,
and return a negative integer if this object is less than,
return a zero if this object is equal,
return a positive integer if this object is greater than,
the specified object o.
21
• Example1
public class ComparableDemo01{

public static void main(String[] args) {


Person p1 = new Person(“Lele", 10, “ School One");
Person p2 = new Person (“Sara" , 15 , “ School Two") ;
Person p3 = new Person( “Ann" , 8 , "School Three");

Person p[ ] = {p1,p2,p3};
System.out.println ("befor comparable") ;
for(Person person:p){
System.out.println(person);
}
java.util.Arrays.sort(p);
System.out.println ("after comparable") ;
for(Person person:p){
System.out.println(person);
}
}
}
class Person implements Comparable<Person>{
private String name;
private int age ;
private String school ;

public Person(String name,int age,String school){


this.name = name ;
this.age = age ;
this.school = school ;
}
public int compareTo(Person t){
if( this.age> t.age){
return -1 ;
}else if(this.age<t.age){
return 1;
}
else{
return 0 ;
} }
public String toString(){
return( this.name + "age" + this.age + "school" +
this.school);
}
}

You might also like