6 1 interface
TRANSCRIPT
-
8/14/2019 6 1 Interface
1/41
1Java
Interface
Part 1
-
8/14/2019 6 1 Interface
2/41
2Java
Result10
Heap class using Comparable objects9
Set Standard- Comparable example8
Set Standard7
Shared constants6
Uses5
Solution to student-teacher problem4Syntax3
Definition2
Dilemma1
contents
-
8/14/2019 6 1 Interface
3/41
3Java
instanceof14Cloneable13
clone() method of Object class12
Tagging11
contents
-
8/14/2019 6 1 Interface
4/41
4Java
Know
What interfaces are and why they are used
What a Marker interface is
-
8/14/2019 6 1 Interface
5/41
5Java
Be Able To
Write programs using interfaces where
appropriate
-
8/14/2019 6 1 Interface
6/41
6Java
Dilemma !
How will we represent a
teacher who is also a
student?
-
8/14/2019 6 1 Interface
7/41
7Java
StudentTeacherStudent
Teacher
-
8/14/2019 6 1 Interface
8/41
8Java
Definition
An interface is a special type of class which may have
b) some constants
c) some methods listed but with no implementations.
Always public, static and final
Always public and abstract
Interface cannot be instantiated.
They dont automatically inherit from Object class.
A class can inherit from more than one interface.
-
8/14/2019 6 1 Interface
9/41
9Java
Syntax
interface interface_name{datatype variable_name=value;
returntype method_name();}
class class_name implements
interface_name{returntype method_name(){}
}
public or static or
final can be
explicitly specifiedbut not necessary.
public or abstract
can be explicitly
specified but not
necessary.
public or default
-
8/14/2019 6 1 Interface
10/41
10Java
TeachingStaff
int getFactId()
void display()
Teacher
int getFactId()
void display()
StudentTeacherStudent
Step 1
Step 2
Step 3StudentTeacher
TeachingStaff
Solution to student-teacher
problem
Indirect relationship through the interface
-
8/14/2019 6 1 Interface
11/41
11Java
package teacher;
public interface TeachingStaff{
// important methods of Teacher class}
package teacher;
public class Teacher implements TeachingStaff{
/* implement all the methods of TeachingStaff*/ }
package student;
import teacher.*;
public class StudentTeacher extends Studentimplements TeachingStaff{
/*implement all the methods of TeachingStaff*/}
-
8/14/2019 6 1 Interface
12/41
12Java
Now before looking at the complete solution, let
me get this straight. Using an Interface will make
me implement all the important methods inside
both the StudentTeacher and Teacher classes. If
that is the case, then why do I need an interface at
all? The main reason we go for inheritance is for
reusability. And I dont see any reusability here. Ineed to copy and paste code from Teacher class
into StudentTeacher class anyway.
-
8/14/2019 6 1 Interface
13/41
13Java
Interface will help you relate classes. Why do I need to
relate ? - Polymorphism!
Lvoid listInvigilators(TeachingStaffs[])for(int i=0;i
-
8/14/2019 6 1 Interface
14/41
14Java
And we have formulated a betterway to implement methods of
interface than copy-paste. Look at
the code in the next slides.
-
8/14/2019 6 1 Interface
15/41
15Java
package teacher;
public interface TeachingStaff{
int getFactId();String getName(); }
-----------------------------------------
package teacher;
public class Teacher extendsgeneral.Personimplements TeachingStaff{
public int getFactId(){ return factId;}
} Note that it is an error if we omit public here
-
8/14/2019 6 1 Interface
16/41
16Java
package student;
import teacher.*;
public class StudentTeacherextendsStudent implements TeachingStaff
{private Teacher t;
public StudentTeacher(String name) {
super(name); t= new Teacher(name);
}
to help us call the teacher
class methods
-
8/14/2019 6 1 Interface
17/41
17Java
public int getFactId()
{return t.getFactId();}
public String getName(){
return t.getName();}
}
Notice how we
use private
reference of
teacher class tocall methods of
the teacher class
in order to avoid
retyping the samecode !
-
8/14/2019 6 1 Interface
18/41
18Java
import teacher.*;import student.*;import admin.*;class Test{static void listInvigilators(TeachingStaffs[]){for(int i=0;i
-
8/14/2019 6 1 Interface
19/41
19Java
Having said so much about interface being used to overcome
multiple inheritance problem, let me also tell you this.
What we have seen is only a small aspect of the benefits that
arise from using interfaces. You will be surprised to know that
interfaces are one of the most important design elements that
are used.
We will not deal with application designing here. There is much
more that we need to learn before we get there.
-
8/14/2019 6 1 Interface
20/41
20Java
Uses
Interfaces are used to
2. overcome the issues that arise because Java does not
support multiple inheritance.
3. used to share constants
4. used to set or define standards
5. used for tagging
6. used as callbacks
We have already seen this
We will see this use when we do
threads and AWT
-
8/14/2019 6 1 Interface
21/41
21Java
Shared constantspublic interface TeachingStaff {
int RETIREMENT_AGE=60;
}
import static teacher.TeachingStaff.
RETIREMENT_AGE;
class AnyClass{
System.out.println(RETIREMENT_AGE);
}
Do you remember this syntax?
-
8/14/2019 6 1 Interface
22/41
22Java
Set Standard
Standards must be set for the
bulb holder so that
b) any bulb can fit into anyholder.
c) it is easy for the bulb factory
to design bulbs.
I am not sure if I willfit into those non-
standard holders !
-
8/14/2019 6 1 Interface
23/41
23Java
Set Standard- Comparable example
Grade
int compareGrades(Grade g)
Will return 0 if grades are same , a value >0
if the current grade is greater than the the
grade object being passed.
Test
void rank(Grade[] g)
Student[] search(Grade g, String grade)
Will use
compareGrades() to
compare the grades
S t St d d C bl
-
8/14/2019 6 1 Interface
24/41
24Java
Set Standard- Comparable
example
Student
int compareTo(Object o)
java.lang.Comparable
int compareTo(Object o)
java.util.Arraysint binarySearch(Object[] a,Object key)
void sort(Object[] a)
Can be used to sort
and search grades
since Grade has
implemented
Comparable
-
8/14/2019 6 1 Interface
25/41
25Java
Why is java compelling me to
implement this interface ?
Think about it. How will the Array class
know how to sort your objects?
In order make sure that grades are sortedproperly java sets the standard by
compelling you to implement the
Comparable interface.
Like Arrays, there are many more classesthat have many more utility methods that
we can make use of if we implement
Comparable interface.
-
8/14/2019 6 1 Interface
26/41
package student;
public class Student extendsgeneral.Person implements Comparable{
public int compareTo(Object o) {
Student s=(Student)o;return
this.getName().compareTo(s.getName());
}}
Folder 2
compareTo() is already overridden in the String class
-
8/14/2019 6 1 Interface
27/41
27Java
Heap class using Comparable
objectspublic class Heap{
private Object heap[];
private int noOfElements;
private int currentPosition=1;
Heap(int noOfElements){
this.noOfElements=noOfElements;heap= new Object[noOfElements+1];
}
-
8/14/2019 6 1 Interface
28/41
28Java
public void insert(Object ele){if(currentPosition>noOfElements+1){System.out.println("Can't add any more!");
return;}else{
heap[currentPosition++]=ele;if(currentPosition-1!=1)
bubbleUp(currentPosition-1);return;
}}
void bubbleUp(int exchangeIndex){if(exchangeIndex==1){ return; }
int parentIndex=exchangeIndex/2;
-
8/14/2019 6 1 Interface
29/41
29Java
Comparablec1=(Comparable)heap[exchangeIndex];Comparable
c2=(Comparable)heap[parentIndex];if(c1.compareTo(c2)
-
8/14/2019 6 1 Interface
30/41
30Java
public void display(){for(int i=1;i
-
8/14/2019 6 1 Interface
31/41
31Java
void heapify(int index){int left=index*2;int right=index*2+1;
int temp=index;if(left0){exchange(index,temp);heapify(index);. }}}
smallest between left and right nodes
Exchange with smaller node
-
8/14/2019 6 1 Interface
32/41
32Java
public void heapSort(){int tot=currentPosition-1;
System.out.println("Heap Sort");for(int i=0;i
-
8/14/2019 6 1 Interface
33/41
33Java
heap.insert(45); heap.insert(21);heap.insert(18); heap.insert(14);heap.insert(60); heap.insert(32);
heap.insert(6); heap.heapSort();Heap sheap =new Heap(4);System.out.println("Inserting students
into heap");sheap.insert(new Student("Rama"));sheap.insert(new Student("Sita"));sheap.insert(new Student("Haunuman"));
sheap.insert(new Student("Ravana"));sheap.heapSort();}
}
-
8/14/2019 6 1 Interface
34/41
34Java
ResultInserting integers into heapHeap Sort
6141821
324560Inserting students into heapHeap SortHaunuman-3Rama-1Ravana-4Sita-2
-
8/14/2019 6 1 Interface
35/41
35Java
When we come to collection
classes, we will be learning
about Arrays class and many
more collection classes. There
make use of Comparable
interface extensively.
-
8/14/2019 6 1 Interface
36/41
36Java
Tagging
Interfaces which do not have any methods are
called Marker interfaces.
Marker interfaces are used to tag a class so that
the class is of the interface type. Some examples of marker interface in JDK are:
d) Cloneable
e) Serializablef) Remote
-
8/14/2019 6 1 Interface
37/41
37Java
clone() method of Object class
Teacher
factid =123
clone()
object
clone()
cloned object is returned
cloned object
Teacher
factid =123
-
8/14/2019 6 1 Interface
38/41
38Java
clone()
object
clone()
Teacher
factid =123
GradeEXCELLIENT1000
GradeEXCELLIENT1000
referenceAddress
1000
cloned object is returned
cloned object
returned
-
8/14/2019 6 1 Interface
39/41
39Java
Cloneable
That is the reason why the clone() method in
Object class is protected.
protected Object clone() throwsCloneNotSupportedException{}
If clone() method has to be given public access
then we need to override it.
To make other objects aware that the clone()method is implemented rightly in this class, this
class must implement the interface Cloneable.
package teacher;
-
8/14/2019 6 1 Interface
40/41
40Java
package teacher;public class Teacher extends general.Personimplements TeachingStaff,Cloneable{
public Object clone()throws
CloneNotSupportedException{return super.clone(); }}
public static void main(String str[]) throws
CloneNotSupportedException{Teacher t1=new Teacher("Gayatri");Teacher t2=(Teacher)t1.clone();t2.setName("Malini");
System.out.println(t1.getFactId()+""+t1.getName());System.out.println(t2.getFactId()+""+t2.getName());}
}
We are ok with the Object
classs clone()
implementation.
Output:
1 Gayatri
1 Malini
Folder 3
-
8/14/2019 6 1 Interface
41/41
41J
instanceof reference instanceof ClassName
We have seen this in the Classes Explored chapter. If the
actual type of referenceon the LHS has no directrelationship with the class on RHS then a compilation
error occurs. Rewriting the same syntax to include
interface also we have,
reference instanceofClassName/InterfaceName
The reference type can be of Interface or Class type.
If LHS or RHS have interface type, then there is no
compilation error that occurs.