SlideShare a Scribd company logo
1 of 18
Interface
• using interface, you can specify what a class
must do, but not how it does it.
• Interfaces are syntactically similar to classes,
but they lack instance variables, and their
methods are declared without any body.
• Through the use of the interface keyword,
Java allows you to fully abstract the interface
from its implementation.
Interface
• Using interface, you can specify a set of
method which can be implemented by one or
more classes.
• The interface, itself, does not actually define
any implementation.
• A class can implement more than one
interface.
• A class can only inherit a single superclass.
Defining an Interface
• The general form :
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;
}
• 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.
• All methods and variables are implicitly public
if the interface, itself, is declared as public.
• Variables can be declared inside of interface
declarations.
• They are implicitly final and static, meaning
they cannot be changed by the implementing
class.
Sample
interface Callback {
void callback(int param);
}
Implementing Interfaces
• To implement an interface, include the
implements clause in a class definition, and
then create the methods defined by the
interface.
• The general form:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
Sample
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces "
+
"may also define other members, too.");
} }
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.
Interface sample
// Define an integer stack interface.
interface IntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}
class FixedStack implements IntStack {
private int stck[];
private int tos;
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
public void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
} }
class IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
Variables in Interfaces
• To import shared constants into multiple
classes by simply declaring an interface that
contains variables which are initialized to the
desired values.
Sample
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 50)
return NO;
else if (prob < 80)
return YES;
else
return NEVER;
}
}
class 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;
} }
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
} }
Interfaces Can Be Extended
• One interface can inherit another by use of the
keyword extends.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds
meth3().
interface B extends A {
void meth3(); }

More Related Content

What's hot

Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
4. java intro class
4. java intro class4. java intro class
4. java intro classQuan Ho
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classesTech_MX
 
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
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear ASHNA nadhm
 
Polymorphism and Software Reuse
Polymorphism and Software ReusePolymorphism and Software Reuse
Polymorphism and Software Reuseadil raja
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
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
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 

What's hot (20)

Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
4. java intro class
4. java intro class4. java intro class
4. java intro class
 
Hemajava
HemajavaHemajava
Hemajava
 
Java keywords
Java keywordsJava keywords
Java keywords
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Inheritance
InheritanceInheritance
Inheritance
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classes
 
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
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Lecture22.23.07.2014
Lecture22.23.07.2014Lecture22.23.07.2014
Lecture22.23.07.2014
 
Interface
InterfaceInterface
Interface
 
Polymorphism and Software Reuse
Polymorphism and Software ReusePolymorphism and Software Reuse
Polymorphism and Software Reuse
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
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
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 

Similar to Implementing Interfaces in Java

Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
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
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Interface
InterfaceInterface
Interfacevvpadhu
 
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
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptxmadan r
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 

Similar to Implementing Interfaces in Java (20)

Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
14 interface
14  interface14  interface
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 Interfaces
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Interface
InterfaceInterface
Interface
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Interfaces
InterfacesInterfaces
Interfaces
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Interface &amp;packages
Interface &amp;packagesInterface &amp;packages
Interface &amp;packages
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Interface
InterfaceInterface
Interface
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Cse java
Cse javaCse java
Cse java
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 

More from GaneshKumarKanthiah (11)

Software testing regression testing
Software testing  regression testingSoftware testing  regression testing
Software testing regression testing
 
Software testing acceptance testing
Software testing  acceptance testingSoftware testing  acceptance testing
Software testing acceptance testing
 
Software testing performance testing
Software testing  performance testingSoftware testing  performance testing
Software testing performance testing
 
Software testing introduction
Software testing  introductionSoftware testing  introduction
Software testing introduction
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java packages
Java packagesJava packages
Java packages
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java awt
Java awtJava awt
Java awt
 
Java applet
Java appletJava applet
Java applet
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 

Implementing Interfaces in Java

  • 2. • using interface, you can specify what a class must do, but not how it does it. • Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. • Through the use of the interface keyword, Java allows you to fully abstract the interface from its implementation.
  • 3. Interface • Using interface, you can specify a set of method which can be implemented by one or more classes. • The interface, itself, does not actually define any implementation. • A class can implement more than one interface. • A class can only inherit a single superclass.
  • 4. Defining an Interface • The general form : 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; }
  • 5. • 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. • All methods and variables are implicitly public if the interface, itself, is declared as public.
  • 6. • Variables can be declared inside of interface declarations. • They are implicitly final and static, meaning they cannot be changed by the implementing class.
  • 7. Sample interface Callback { void callback(int param); }
  • 8. Implementing Interfaces • To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. • The general form: access class classname [extends superclass] [implements interface [,interface...]] { // class-body }
  • 9. Sample class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement interfaces " + "may also define other members, too."); } }
  • 10. 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.
  • 11. Interface sample // Define an integer stack interface. interface IntStack { void push(int item); // store an item int pop(); // retrieve an item } class FixedStack implements IntStack { private int stck[]; private int tos; FixedStack(int size) { stck = new int[size]; tos = -1; }
  • 12. public void push(int item) { if(tos==stck.length-1) // use length member System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack public int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } }
  • 13. class IFTest { public static void main(String args[]) { FixedStack mystack1 = new FixedStack(5); FixedStack mystack2 = new FixedStack(8); // push some numbers onto the stack for(int i=0; i<5; i++) mystack1.push(i); for(int i=0; i<8; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<5; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<8; i++) System.out.println(mystack2.pop()); }
  • 14. Variables in Interfaces • To import shared constants into multiple classes by simply declaring an interface that contains variables which are initialized to the desired values.
  • 15. Sample import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; }
  • 16. class Question implements SharedConstants { Random rand = new Random(); int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 50) return NO; else if (prob < 80) return YES; else return NEVER; } }
  • 17. class 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; } } public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } }
  • 18. Interfaces Can Be Extended • One interface can inherit another by use of the keyword extends. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() -- it adds meth3(). interface B extends A { void meth3(); }