SlideShare una empresa de Scribd logo
1 de 35
Interfaces in JAVA
By Jai Vikas Marathe
Agenda
What is Interface?
Why Interface?
Interface as a Type
Interface vs. Class
Defining an Interface
Implementing an Interface
Implementing multiple Interface's
Inheritance among Interface's
Rewriting an Interface
What is an Interface?
What is an Interface?
It defines a standard and public way of specifying the
behaviour of classes
All methods of an interface are abstract methods
Example: Interface
// Note that Interface contains just set of
method
// signatures without any implementations.
// No need to say abstract modifier for each
method
// since it assumed.
public interface Relation {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
Example 2: Interface
public interface OperateCar {
// constant declarations, if any
// method signatures
int turn(Direction direction, double radius,
double startSpeed, double endSpeed);
int changeLanes(Direction direction, double
startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean
signalOn);
int getRadarFront(double distanceToCar, double
speedOfCar);
Why Interface?
Why do we use Interfaces?
Reason #1
To reveal an object's programming interface
(functionality of the object) without revealing its
implementation
Why do we use Interfaces?
Reason #2
To have unrelated classes implement similar methods
(behaviours)
Example:
Class Line and class MyInteger
Interface:
checkIsGreater(Object x, Object y)
checkIsLess(Object x, Object y)
checkIsEqual(Object x, Object y)
Why do we use Interfaces?
Reason #3
To model multiple inheritance
Interface vs. Abstract Class
All methods of an Interface are abstract methods while
some methods of an Abstract class are abstract methods
An interface can only define constants while abstract
class can have fields
Interfaces have no direct inherited relationship with any
particular class, they are defined independently
Interface as a
Type
Interface as a Type
When you define a new interface, you are defining a
new reference type
You can use interface names anywhere you can use any
other type name
If you define a reference variable whose type is an
interface, any object you assign to it must be an instance
of a class that implements the interface
Example: Interface as a Type
Let's say Person class implements PersonInterface
interface
You can do
– Person p1 = new Person();
– PersonInterface pi1 = p1;
– PersonInterface pi2 = new Person();
Interface vs. Class
Interface vs. Class:
Commonality
Interfaces and classes are both types
– For example:
// Recommended practice
PersonInterface pi = new Person();
Interface and Class can both define methods
Interface vs. Class:
DifferencesThe methods of an Interface are all abstract methods
You cannot create an instance from an interface
– For example:
PersonInterface pi = new PersonInterface();
//ERROR!
An interface can only be implemented by classes or
extended by other interfaces
Defining Interface
Defining Interface
To define an interface, we write:
public interface [InterfaceName] {
//some methods without the body
}
Example
public interface Relation {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Implementing
Interface
Implementing Interface
public class Line implements Relation {
private double x1;
private double x2;
private double y1;
private double y2;
public Line(double x1, double x2, double y1, double y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
} // More code follows
Implementing Interface
public double getLength(){
double length = Math.sqrt((x2-x1)*(x2-x1) +
(y2-y1)* (y2-y1));
return length;
}
public boolean isGreater( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);}
Implementing Interface
public boolean isLess( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}
public boolean isEqual( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}}
Implementing Interface
Line.java:4: Line is not abstract and does not
override abstract method
isGreater(java.lang.Object,java.lang.Object) in
Relation
public class Line implements Relation
^
1 error
Implementing
Multiple
Interfaces
Relationship of an Interface to
a Class
A sub class can only extend one super class, but it can
implement multiple Interfaces
All abstract methods of all interfaces have to be
implemented by the sub class
Example
A sub class extends one super class but multiple
Interfaces:
public class ComputerScienceStudent
extends Student
implements PersonInterface,
AnotherInterface,
Thirdinterface{
// All abstract methods of all interfaces
// need to be implemented.}
Inheritance
Among Interfaces
Inheritance Among Interfaces
Interfaces can have inheritance relationship among
themselves
public interface PersonInterface {
void doSomething();
}
public interface StudentInterface extends
PersonInterface {
void doExtraSomething();
}
Rewriting Interfaces
Problem
Consider an interface that you have developed called DoIt:
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
}
Problem…
Suppose that, at a later time, you want to add a third
method to DoIt, so that the interface now becomes:
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x, String s);
}
8/16/13
Solution of Rewriting an
Existing Interface
For example, you could create a DoItPlus interface that
extends DoIt:
public interface DoItPlus extends DoIt {
boolean didItWork(int i, double x, String
s);
}
Thank You…!

Más contenido relacionado

La actualidad más candente

Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismJawad Khan
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend classAbhishek Wadhwa
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 InterfaceOUM SAOKOSAL
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceOum Saokosal
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsSanmatiRM
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - PolymorphismMudasir Qazi
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++ shammi mehra
 

La actualidad más candente (20)

Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Oops in vb
Oops in vbOops in vb
Oops in vb
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphism
 
Oops
OopsOops
Oops
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Friend Function
Friend FunctionFriend Function
Friend Function
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Similar a Interfaces

Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Abou Bakr Ashraf
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.pptVISHNUSHANKARSINGH3
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
pbo 5 ervan
pbo 5 ervanpbo 5 ervan
pbo 5 ervanaris
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfTabassumMaktum
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptTabassumMaktum
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptTabassumMaktum
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 

Similar a Interfaces (20)

Java interface
Java interfaceJava interface
Java interface
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Basic_Java_10.pdf
Basic_Java_10.pdfBasic_Java_10.pdf
Basic_Java_10.pdf
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Java Interface
Java InterfaceJava Interface
Java Interface
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Java interface
Java interface Java interface
Java interface
 
pbo 5 ervan
pbo 5 ervanpbo 5 ervan
pbo 5 ervan
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdf
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .ppt
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .ppt
 
Interface
InterfaceInterface
Interface
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Último

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 

Último (20)

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 

Interfaces

  • 1. Interfaces in JAVA By Jai Vikas Marathe
  • 2. Agenda What is Interface? Why Interface? Interface as a Type Interface vs. Class Defining an Interface Implementing an Interface Implementing multiple Interface's Inheritance among Interface's Rewriting an Interface
  • 3. What is an Interface?
  • 4. What is an Interface? It defines a standard and public way of specifying the behaviour of classes All methods of an interface are abstract methods
  • 5. Example: Interface // Note that Interface contains just set of method // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b);
  • 6. Example 2: Interface public interface OperateCar { // constant declarations, if any // method signatures int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar);
  • 8. Why do we use Interfaces? Reason #1 To reveal an object's programming interface (functionality of the object) without revealing its implementation
  • 9. Why do we use Interfaces? Reason #2 To have unrelated classes implement similar methods (behaviours) Example: Class Line and class MyInteger Interface: checkIsGreater(Object x, Object y) checkIsLess(Object x, Object y) checkIsEqual(Object x, Object y)
  • 10. Why do we use Interfaces? Reason #3 To model multiple inheritance
  • 11. Interface vs. Abstract Class All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods An interface can only define constants while abstract class can have fields Interfaces have no direct inherited relationship with any particular class, they are defined independently
  • 13. Interface as a Type When you define a new interface, you are defining a new reference type You can use interface names anywhere you can use any other type name If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
  • 14. Example: Interface as a Type Let's say Person class implements PersonInterface interface You can do – Person p1 = new Person(); – PersonInterface pi1 = p1; – PersonInterface pi2 = new Person();
  • 16. Interface vs. Class: Commonality Interfaces and classes are both types – For example: // Recommended practice PersonInterface pi = new Person(); Interface and Class can both define methods
  • 17. Interface vs. Class: DifferencesThe methods of an Interface are all abstract methods You cannot create an instance from an interface – For example: PersonInterface pi = new PersonInterface(); //ERROR! An interface can only be implemented by classes or extended by other interfaces
  • 19. Defining Interface To define an interface, we write: public interface [InterfaceName] { //some methods without the body }
  • 20. Example public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); }
  • 22. Implementing Interface public class Line implements Relation { private double x1; private double x2; private double y1; private double y2; public Line(double x1, double x2, double y1, double y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } // More code follows
  • 23. Implementing Interface public double getLength(){ double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)); return length; } public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen);}
  • 24. Implementing Interface public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen); } public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); }}
  • 25. Implementing Interface Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation public class Line implements Relation ^ 1 error
  • 27. Relationship of an Interface to a Class A sub class can only extend one super class, but it can implement multiple Interfaces All abstract methods of all interfaces have to be implemented by the sub class
  • 28. Example A sub class extends one super class but multiple Interfaces: public class ComputerScienceStudent extends Student implements PersonInterface, AnotherInterface, Thirdinterface{ // All abstract methods of all interfaces // need to be implemented.}
  • 30. Inheritance Among Interfaces Interfaces can have inheritance relationship among themselves public interface PersonInterface { void doSomething(); } public interface StudentInterface extends PersonInterface { void doExtraSomething(); }
  • 32. Problem Consider an interface that you have developed called DoIt: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); }
  • 33. Problem… Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); boolean didItWork(int i, double x, String s); } 8/16/13
  • 34. Solution of Rewriting an Existing Interface For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); }