SlideShare una empresa de Scribd logo
1 de 25
JAVA

INTERFACES
Interfaces
What is an Interface?
Creating an Interface
Implementing an Interface
What is Marker Interface?
Inheritance
OOP allows you to derive new classes from existing
classes. This is called inheritance.
Inheritance is an important and powerful concept in
Java. Every class you define in Java is inherited from
an existing class.
 Sometimes it is necessary to derive a subclass from
several classes, thus inheriting their data and methods.
In Java only one parent class is allowed.
With interfaces, you can obtain effect of multiple
inheritance.
What is an Interface?
An interface is a classlike construct that contains only
constants and abstract methods.
Cannot be instantiated. Only classes that implements
interfaces can be instantiated. However, final
public static variables can be defined to interface
types.
Why not just use abstract classes? Java does not permit
multiple inheritance from classes, but permits
implementation of multiple interfaces.
What is an Interface?
Protocol for classes that completely separates
specification/behaviour from implementation.

One class can implement many interfaces

One interface can be implemented by many classes

By providing the interface keyword, Java allows you
to fully utilize the "one interface, multiple methods"
aspect of polymorphism.
Why an Interface?
Normally, in order for a method to be called from one
class to another, both classes need to be present at
compile time so the Java compiler can check to ensure
that the method signatures are compatible.
In a system like this, functionality gets pushed up
higher and higher in the class hierarchy so that the
mechanisms will be available to more and more
subclasses.
Interfaces are designed to avoid this problem.
Interfaces are designed to support dynamic method
resolution at run time.
Why an Interface?
Interfaces are designed to avoid this problem.
They disconnect the definition of a method or set of
methods from the inheritance hierarchy.
Since interfaces are in a different hierarchy from classes,
it is possible for classes that are unrelated in terms of the
class hierarchy to implement the same interface.
This is where the real power of interfaces is realized.
Creating an Interface
File InterfaceName.java:
modifier interface InterfaceName
{
  constants declarations;
  methods signatures;
}
Modifier is public or not used.

File ClassName.java:
modifier Class ClassName implements InterfaceName
{
   methods implementation;
}
If a class implements an interface, it should override all
the abstract methods declared in the interface.
Creating an Interface
public interface MyInterface
{
  public void aMethod1(int i); // an abstract methods
  public void aMethod2(double a);
...
  public void aMethodN();

}

public Class    MyClass implements MyInterface
{
  public void   aMethod1(int i) { // implementaion }
  public void   aMethod2(double a) { // implementaion }
  ...
  public void   aMethodN() { // implementaion }
}
Creating a Multiple Interface
modifier interface InterfaceName1 {
    methods1 signatures;
}
modifier interface InterfaceName2 {
    methods2 signatures;
}
...
modifier interface InterfaceNameN {
    methodsN signatures;
}
Creating a Multiple Interface
If a class implements a multiple interfaces, it should
 override all the abstract methods declared in all the
interfaces.
public Class ClassName implements InterfaceName1,
                InterfaceName2, …, InterfaceNameN
{
  methods1 implementation;
  methods2 implementation;
  ...
  methodsN implementation;
}
Example of Creating an Interface

// This interface is defined in
// java.lang package
public interface Comparable
{
  public int compareTo(Object obj);
}
Comparable Circle
public interface Comparable
{
  public int compareTo(Object obj);
}
public Class Circle extends Shape
                            implements Comparable {
   public int compareTo(Object o) {
      if (getRadius() > ((Circle)o).getRadius())
        return 1;
      else if (getRadius()<((Circle)o).getRadius())
        return -1;
      else
         return 0;
   }
}
Comparable Cylinder
public Class Cylinder extends Circle
                     implements Comparable {
    public int compareTo(Object o) {
      if(findVolume() > ((Cylinder)o).findVolume())
         return 1;
      else if(findVolume()<((Cylinder)o).findVolume())
         return -1;
      else
        return 0;
  }
}
Generic findMax Method
public class Max
{
    // Return the maximum between two objects
    public static Comparable findMax(Comparable ob1,
                                Comparable ob2)
    {
      if (ob1.compareTo(ob2) > 0)
         return ob1;
      else
         return ob2;
    }
}
Access via interface reference
You can declare variables as object references that use an interface
rather than a class type. Any instance of any class that implements
the declared interface can be stored in such a variable.
Example: Comparable circle;
When you call a method through one of these references, the
correct version will be called based on the actual instance of the
interface being referred to.
Example: circle = Max.findMax(circle1, circle2);
Using Interface
This is one of the key features of interfaces.
  The method to be executed is looked up dynamically at
  run time, allowing classes to be created later than the
  code which calls methods on them.
  The calling code can dispatch through an interface
  without having to know anything about the "callee."
Using Interface
Objective: Use the findMax() method to find a
 maximum circle between two circles:
Circle circle1 = new Circle(5);
Circle circle2 = new Circle(10);
Comparable circle = Max.findMax(circle1, circle2);
System.out.println(((Circle)circle).getRadius());
// 10.0
System.out.println(circle.toString());
// [Circle] radius = 10.0
Interfaces vs. Abstract Classes
♦ 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. An abstract class must contain at
 least one abstract method or inherit from
 another abstract method.
Interfaces vs. Abstract Classes,
              cont.

Since all the methods defined in an interface
are abstract methods, Java does not require
you to put the abstract modifier in the
methods in an interface, but you must put the
abstract modifier before an abstract
method in an abstract class.
Interfaces & Classes
  Interface1_2                        Interface2_2



  Interface1_1      Interface1        Interface2_1




   Object            Class1                             Class2

• One interface can inherit another by use of the keyword extends.
   The syntax is the same as for inheriting classes.
• When a class implements an interface that inherits another
  interface, it must provide implementations for all methods
  defined within the interface inheritance chain.
Interfaces & Classes, cont.
public Interface1_1 { … }   Interface1_2                Interface2_2


public Interface1_2 { … }   Interface1_1   Interface1   Interface2_1

public Interface2_1 { … }
public Interface2_2 { … }   Object          Class1                     Class2




public Interface1 extends Interface1_1, Interface1_2
{...}

public abstract Class Class1 implements Interface1
{... }

public Class Class2 extends Class1 implements
Interface2_1, Interface2_2 {...}
Interfaces vs. Absract Classes
♦ A strong is-a relationship that clearly describes a parent-child
relationship should be modeled using classes.
 Example: a staff member is a person.

♦ A weak is-a relationship, also known as a-kind-of
relationship, indicates that an object possesses a certain
property.
 Example: all strings are comparable, so the String class
 implements the Comparable interface.

♦ The interface names are usually adjectives. You can also use
interfaces to circumvent single inheritance restriction if multiple
inheritance is desired. You have to design one as a superclass,
and the others as interfaces.
The Cloneable Interfaces
Marker Interface: An empty interface.
A marker interface does not contain constants
or methods, but it has a special meaning to the
Java system. The Java system requires a class
to implement the Cloneable interface to
become cloneable.
public interface Cloneable
{
}
The Cloneable Interfaces
public Class Circle extends Shape
                        implements Cloneable {
  public Object clone() {
    try {
        return super.clone()
    }
    catch (CloneNotSupportedException ex) {
         return null;
    }
  }
  ------------------------------------------
  Circle c1 = new Circle(1,2,3);
  Circle c2 = (Circle)c1.clone();

  This is shallow copying with super.clone() method.
  Override the method for deep copying.

Más contenido relacionado

La actualidad más candente

oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

La actualidad más candente (20)

Applets in java
Applets in javaApplets in java
Applets in java
 
Java interface
Java interfaceJava interface
Java interface
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Interface
InterfaceInterface
Interface
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java threads
Java threadsJava threads
Java threads
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 

Similar a Java interfaces

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
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
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdfAdilAijaz3
 
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
 
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
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
Interface
InterfaceInterface
Interfacevvpadhu
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.pptVarunP31
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 

Similar a Java interfaces (20)

Interfaces
InterfacesInterfaces
Interfaces
 
Java 06
Java 06Java 06
Java 06
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
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
 
Interface
InterfaceInterface
Interface
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
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 mcq
Java mcqJava mcq
Java mcq
 
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
 
Inheritance
InheritanceInheritance
Inheritance
 
Java interface
Java interfaceJava interface
Java interface
 
Java Interface
Java InterfaceJava Interface
Java Interface
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Interface
InterfaceInterface
Interface
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 

Más de Raja Sekhar

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsRaja Sekhar
 

Más de Raja Sekhar (8)

Exception handling
Exception handlingException handling
Exception handling
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java packages
Java packagesJava packages
Java packages
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Java Starting
Java StartingJava Starting
Java Starting
 

Último

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Java interfaces

  • 2. Interfaces What is an Interface? Creating an Interface Implementing an Interface What is Marker Interface?
  • 3. Inheritance OOP allows you to derive new classes from existing classes. This is called inheritance. Inheritance is an important and powerful concept in Java. Every class you define in Java is inherited from an existing class. Sometimes it is necessary to derive a subclass from several classes, thus inheriting their data and methods. In Java only one parent class is allowed. With interfaces, you can obtain effect of multiple inheritance.
  • 4. What is an Interface? An interface is a classlike construct that contains only constants and abstract methods. Cannot be instantiated. Only classes that implements interfaces can be instantiated. However, final public static variables can be defined to interface types. Why not just use abstract classes? Java does not permit multiple inheritance from classes, but permits implementation of multiple interfaces.
  • 5. What is an Interface? Protocol for classes that completely separates specification/behaviour from implementation. One class can implement many interfaces One interface can be implemented by many classes By providing the interface keyword, Java allows you to fully utilize the "one interface, multiple methods" aspect of polymorphism.
  • 6. Why an Interface? Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the Java compiler can check to ensure that the method signatures are compatible. In a system like this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. Interfaces are designed to support dynamic method resolution at run time.
  • 7. Why an Interface? Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface. This is where the real power of interfaces is realized.
  • 8. Creating an Interface File InterfaceName.java: modifier interface InterfaceName { constants declarations; methods signatures; } Modifier is public or not used. File ClassName.java: modifier Class ClassName implements InterfaceName { methods implementation; } If a class implements an interface, it should override all the abstract methods declared in the interface.
  • 9. Creating an Interface public interface MyInterface { public void aMethod1(int i); // an abstract methods public void aMethod2(double a); ... public void aMethodN(); } public Class MyClass implements MyInterface { public void aMethod1(int i) { // implementaion } public void aMethod2(double a) { // implementaion } ... public void aMethodN() { // implementaion } }
  • 10. Creating a Multiple Interface modifier interface InterfaceName1 { methods1 signatures; } modifier interface InterfaceName2 { methods2 signatures; } ... modifier interface InterfaceNameN { methodsN signatures; }
  • 11. Creating a Multiple Interface If a class implements a multiple interfaces, it should override all the abstract methods declared in all the interfaces. public Class ClassName implements InterfaceName1, InterfaceName2, …, InterfaceNameN { methods1 implementation; methods2 implementation; ... methodsN implementation; }
  • 12. Example of Creating an Interface // This interface is defined in // java.lang package public interface Comparable { public int compareTo(Object obj); }
  • 13. Comparable Circle public interface Comparable { public int compareTo(Object obj); } public Class Circle extends Shape implements Comparable { public int compareTo(Object o) { if (getRadius() > ((Circle)o).getRadius()) return 1; else if (getRadius()<((Circle)o).getRadius()) return -1; else return 0; } }
  • 14. Comparable Cylinder public Class Cylinder extends Circle implements Comparable { public int compareTo(Object o) { if(findVolume() > ((Cylinder)o).findVolume()) return 1; else if(findVolume()<((Cylinder)o).findVolume()) return -1; else return 0; } }
  • 15. Generic findMax Method public class Max { // Return the maximum between two objects public static Comparable findMax(Comparable ob1, Comparable ob2) { if (ob1.compareTo(ob2) > 0) return ob1; else return ob2; } }
  • 16. Access via interface reference You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be stored in such a variable. Example: Comparable circle; When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. Example: circle = Max.findMax(circle1, circle2);
  • 17. Using Interface This is one of the key features of interfaces. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them. The calling code can dispatch through an interface without having to know anything about the "callee."
  • 18. Using Interface Objective: Use the findMax() method to find a maximum circle between two circles: Circle circle1 = new Circle(5); Circle circle2 = new Circle(10); Comparable circle = Max.findMax(circle1, circle2); System.out.println(((Circle)circle).getRadius()); // 10.0 System.out.println(circle.toString()); // [Circle] radius = 10.0
  • 19. Interfaces vs. Abstract Classes ♦ 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. An abstract class must contain at least one abstract method or inherit from another abstract method.
  • 20. Interfaces vs. Abstract Classes, cont. Since all the methods defined in an interface are abstract methods, Java does not require you to put the abstract modifier in the methods in an interface, but you must put the abstract modifier before an abstract method in an abstract class.
  • 21. Interfaces & Classes Interface1_2 Interface2_2 Interface1_1 Interface1 Interface2_1 Object Class1 Class2 • One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. • When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.
  • 22. Interfaces & Classes, cont. public Interface1_1 { … } Interface1_2 Interface2_2 public Interface1_2 { … } Interface1_1 Interface1 Interface2_1 public Interface2_1 { … } public Interface2_2 { … } Object Class1 Class2 public Interface1 extends Interface1_1, Interface1_2 {...} public abstract Class Class1 implements Interface1 {... } public Class Class2 extends Class1 implements Interface2_1, Interface2_2 {...}
  • 23. Interfaces vs. Absract Classes ♦ A strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes. Example: a staff member is a person. ♦ A weak is-a relationship, also known as a-kind-of relationship, indicates that an object possesses a certain property. Example: all strings are comparable, so the String class implements the Comparable interface. ♦ The interface names are usually adjectives. You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. You have to design one as a superclass, and the others as interfaces.
  • 24. The Cloneable Interfaces Marker Interface: An empty interface. A marker interface does not contain constants or methods, but it has a special meaning to the Java system. The Java system requires a class to implement the Cloneable interface to become cloneable. public interface Cloneable { }
  • 25. The Cloneable Interfaces public Class Circle extends Shape implements Cloneable { public Object clone() { try { return super.clone() } catch (CloneNotSupportedException ex) { return null; } } ------------------------------------------ Circle c1 = new Circle(1,2,3); Circle c2 = (Circle)c1.clone(); This is shallow copying with super.clone() method. Override the method for deep copying.