SlideShare a Scribd company logo
1 of 16
Download to read 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

More Related Content

What's hot

8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
Tuan Ngo
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
Linh Lê
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
Terry Yoast
 

What's hot (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
 

Similar to 14 interface

Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
Rakesh Madugula
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
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
RudranilDas11
 

Similar to 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
 

More from 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
 

Recently uploaded

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
Safe Software
 
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
Safe Software
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
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
 
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
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
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...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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
 
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...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

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