SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
Interfaces
• A collection of methods which are public and abstract by
default.
• Methods do not have any method body related to the
interface in which these are declared.
• Using interface, you can specify what a class must do, but
not how it does it.
• Once it is defined, any number of classes can implement an
interface. Also, one class can implement any number of
interfaces.
• A class can inherit any number of interfaces. Thus allowing
multiple inheritance in java.
• “one interface, multiple methods” aspect of polymorphism.
Defining an Interface
• An interface is defined much like a classbut using interface keyword.
• general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
• Here, access is either public or not used.
• When no access specifier is included, then default access
results, and the interface is only available to other
members of the package in which it is declared. When it is
declared as public, the interface can be used by any other
code.
• The methods are abstract methods; there can be no
default implementation of any method specified within an
interface. Each class that includes an interface must
implement all of the methods.
• Variables can be declared inside of interface declarations.
They are implicitly final and static, meaning they cannot be
changed by the implementing class. They must also be
initialized with a constant value. All methods and variables
are implicitly public if the interface, itself, is declared as
public.
Implementing Interfaces
• Once an interface has been defined, one or more
classes can implement that interface.
• To implement an interface, include the implements
clause in a class definition, and then create the
methods defined by the interface. The general form of
a class that includes the implements clause looks like
this:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
• Here, access is either public or not used.
• If a class implements more than one interface,
the interfaces are separated with a comma.
• The methods that implement an interface
must be declared public.
• Also, the type signature of the implementing
method must match exactly the type signature
specified in the interface definition.
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void disp() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
* When you implement an interface method, it must be
declared as public.
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}
• The variable c is declared to be of the interface type Callback, yet it
was assigned an instance of Client. Although c can be used to access
the callback( ) method, it cannot access any other members of the
Client class.
• An interface reference variable only has knowledge of the methods
declared by its interface declaration.
• Thus, c could not be used to access disp( ) since it is defined by
Client but not Callback.
Partial Implementations
• If a class includes an interface but does not fully implement the
methods defined by that interface, then that class must be
declared as abstract.
abstract class Incomplete implements Callback {
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
• Any class that inherits Incompete must implement callback() or
to be declared abstract itself
Interfaces Can Be Extended
• One interface can inherit another by use of the keyword extends.
The syntax is the same as for inheriting classes.
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
• Any class that implements B must define all the methods,
otherwise this will cause a compile time error.
• because any class that implements an interface must implement all
methods defined by that interface, including any that are inherited
from other interfaces.
Variables in interface.
• You can use interfaces to import shared constants
into multiple classes by simply declaring an
interface that contains variables which are
initialized to the desired values.
• When we implements that interface in a class all
of those variable names will be in scope as
constants.
• If an interface contains no methods, then any
class that includes such an interface doesn’t
actually implement anything.
Example- variables in interface
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants {
Random randm = new Random();
int ask() {
int prob = (int) (100 * randm.nextDouble());
//above statement returns random numbers in range 0.0 to 1.0
if (prob < 30)
return NO; // 30%
else if (prob < 60)
return YES; // 30%
else if (prob < 75)
return LATER; // 15%
else if (prob < 98)
return SOON; // 13%
else
return NEVER; // 2%
}
}
AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Difference between
Interface
and
Abstract class
INTERFACE ASTRACT CLASS
Multiple inheritance is possible Not possible
Implement is used extends is used
By default all methods are public and
abstract
Methods have to be tagged as public or
abstract
No implementation at all Can have partial implementation
All methods in the interface need to be
overridden
Only abstract methods need to be
overridden
All instance varible in the interface are by
default public, static and final
It is required to be declared as public,
static and final
Do not have any constructor Abstract classes can have constructor
Can not be static Non abstract method can be static

Mais conteúdo relacionado

Mais procurados

Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces Tuan Ngo
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
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
 
New features in java se 8
New features in java se 8New features in java se 8
New features in java se 8melaniamitisor
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05Terry Yoast
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & 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
 

Mais procurados (20)

Interface in java
Interface in javaInterface in java
Interface in java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Java interface
Java interfaceJava interface
Java interface
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Chap04
Chap04Chap04
Chap04
 
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
 
New features in java se 8
New features in java se 8New features in java se 8
New features in java se 8
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Inheritance
InheritanceInheritance
Inheritance
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Java interface
Java interfaceJava interface
Java interface
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 

Semelhante a 14 interface

Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 
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
 
Interface
InterfaceInterface
Interfacevvpadhu
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class featuresRakesh Madugula
 
Binding,interface,abstarct class
Binding,interface,abstarct classBinding,interface,abstarct class
Binding,interface,abstarct classvishal choudhary
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
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
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#Sireesh K
 
ABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptJayanthiM15
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxRudranilDas11
 

Semelhante a 14 interface (20)

Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
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
 
Java interface
Java interfaceJava interface
Java interface
 
Interface
InterfaceInterface
Interface
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Interface
InterfaceInterface
Interface
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Binding,interface,abstarct class
Binding,interface,abstarct classBinding,interface,abstarct class
Binding,interface,abstarct class
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
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
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
8abstact class in c#
8abstact class in c#8abstact class in c#
8abstact class in c#
 
ABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.pptABSTRACT CLASSES AND INTERFACES.ppt
ABSTRACT CLASSES AND INTERFACES.ppt
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Opps
OppsOpps
Opps
 

Mais de Ravindra Rathore

Mais de Ravindra Rathore (12)

Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
 
Line coding
Line coding Line coding
Line coding
 
28 networking
28  networking28  networking
28 networking
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
15 bitwise operators
15 bitwise operators15 bitwise operators
15 bitwise operators
 
Flipflop
FlipflopFlipflop
Flipflop
 

Último

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Último (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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...
 
+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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

14 interface

  • 1. Interfaces • A collection of methods which are public and abstract by default. • Methods do not have any method body related to the interface in which these are declared. • Using interface, you can specify what a class must do, but not how it does it. • Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. • A class can inherit any number of interfaces. Thus allowing multiple inheritance in java. • “one interface, multiple methods” aspect of polymorphism.
  • 2. Defining an Interface • An interface is defined much like a classbut using interface keyword. • general form of an interface: access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; }
  • 3. • Here, access is either public or not used. • When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code. • The methods are abstract methods; there can be no default implementation of any method specified within an interface. Each class that includes an interface must implement all of the methods. • Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they cannot be changed by the implementing class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public.
  • 4. Implementing Interfaces • Once an interface has been defined, one or more classes can implement that interface. • To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: access class classname [extends superclass] [implements interface [,interface...]] { // class-body }
  • 5. • Here, access is either public or not used. • If a class implements more than one interface, the interfaces are separated with a comma. • The methods that implement an interface must be declared public. • Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.
  • 6. interface Callback { void callback(int param); } class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } void disp() { System.out.println("Classes that implement interfaces " + "may also define other members, too."); } } * When you implement an interface method, it must be declared as public.
  • 7. class TestIface { public static void main(String args[]) { Callback c = new Client(); c.callback(42); } } • The variable c is declared to be of the interface type Callback, yet it was assigned an instance of Client. Although c can be used to access the callback( ) method, it cannot access any other members of the Client class. • An interface reference variable only has knowledge of the methods declared by its interface declaration. • Thus, c could not be used to access disp( ) since it is defined by Client but not Callback.
  • 8. Partial Implementations • If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. abstract class Incomplete implements Callback { int a, b; void show() { System.out.println(a + " " + b); } // ... } • Any class that inherits Incompete must implement callback() or to be declared abstract itself
  • 9. Interfaces Can Be Extended • One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. // One interface can extend another. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() -- it adds meth3(). interface B extends A { void meth3(); } • Any class that implements B must define all the methods, otherwise this will cause a compile time error. • because any class that implements an interface must implement all methods defined by that interface, including any that are inherited from other interfaces.
  • 10. Variables in interface. • You can use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables which are initialized to the desired values. • When we implements that interface in a class all of those variable names will be in scope as constants. • If an interface contains no methods, then any class that includes such an interface doesn’t actually implement anything.
  • 11. Example- variables in interface import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; }
  • 12. class Question implements SharedConstants { Random randm = new Random(); int ask() { int prob = (int) (100 * randm.nextDouble()); //above statement returns random numbers in range 0.0 to 1.0 if (prob < 30) return NO; // 30% else if (prob < 60) return YES; // 30% else if (prob < 75) return LATER; // 15% else if (prob < 98) return SOON; // 13% else return NEVER; // 2% } }
  • 13. AskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later"); break;
  • 14. case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break; } } public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } }
  • 16. INTERFACE ASTRACT CLASS Multiple inheritance is possible Not possible Implement is used extends is used By default all methods are public and abstract Methods have to be tagged as public or abstract No implementation at all Can have partial implementation All methods in the interface need to be overridden Only abstract methods need to be overridden All instance varible in the interface are by default public, static and final It is required to be declared as public, static and final Do not have any constructor Abstract classes can have constructor Can not be static Non abstract method can be static