SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere Àhnliche Inhalte

Was ist angesagt?

Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
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
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In JavaCharthaGaglani
 
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
 
Strings in Java
Strings in JavaStrings in Java
Strings in JavaAbhilash Nair
 
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 I/o streams
Java I/o streamsJava I/o streams
Java I/o streamsHamid Ghorbani
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in JavaNaz Abdalla
 
Java package
Java packageJava package
Java packageCS_GDRCST
 

Was ist angesagt? (20)

Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
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
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
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
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
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 I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java IO
Java IOJava IO
Java IO
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java package
Java packageJava package
Java package
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 

Ähnlich wie Java interfaces

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdfAdilAijaz3
 
Lecture 18
Lecture 18Lecture 18
Lecture 18talha ijaz
 
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
 
Inheritance
InheritanceInheritance
Inheritanceabhay singh
 
Java interface
Java interfaceJava interface
Java interfaceArati Gadgil
 
Java Interface
Java InterfaceJava Interface
Java InterfaceManish Tiwari
 
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 .pptAsifMulani17
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.pptVarunP31
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 

Ähnlich wie Java interfaces (20)

Interfaces
InterfacesInterfaces
Interfaces
 
Java 06
Java 06Java 06
Java 06
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
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
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 

Mehr von Raja Sekhar

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Java packages
Java packagesJava packages
Java packagesRaja 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
 
Java Starting
Java StartingJava Starting
Java StartingRaja Sekhar
 

Mehr von 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
 

KĂŒrzlich hochgeladen

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

KĂŒrzlich hochgeladen (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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
 
+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...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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.