SlideShare une entreprise Scribd logo
1  sur  28
Chapter 8



Interface



            http://www.java2all.com
Interface



            http://www.java2all.com
Interfaces are similar to abstract classes, but
differ in their functionality.

   In interfaces, none of the methods are
implemented means interfaces defines methods
without body.

    Interfaces are syntactically similar to classes, but
they lack instance variables, and their methods are
declared without any body.
    But, it can contain final variables, which must
be initialized with values.
                                             http://www.java2all.com
Once it is defined, any number of classes can
implement an interface.
      One class can implement any number of
interfaces

     If we are implementing an interface in a class
we must implement all the methods defined in the
interface as well as a class can also implement its
own methods.

     Interfaces add most of the functionality that is
required for many applications which would
normally resort to using multiple inheritance in C+
+.                                           http://www.java2all.com
Defining Interface



                     http://www.java2all.com
Syntax :

[Access-specifier] interface interface-name
{
     Access-specifier return-type method-
name(parameter-list);
     final type var1=value;
}




                                          http://www.java2all.com
Where, Access-specifier is either public or it is
not given.

     When no access specifier is used, it results into
default access specifier and if interface has default
access specifier then it is only available to other
members of the same package.

        When it is declared as public, the interface can
be used by any other code of other package.
       
        Interface-Name: name of an interface, it can be 
any valid identifier. 
                                              http://www.java2all.com
Any class that includes an interface must
implement all of the methods. Variables can be
declared inside interface declarations.


     They are implicitly final and static, means they
can not be changed by implementing it in a class.
They must also be initialized with a constant value.



                                             http://www.java2all.com
EX :
interface Item
{
    static final int code = 100;
    static final String name = "Fan";
    void display ( );
}

interface Area
{
    static final float pi = 3.14F;
    float compute ( float x, float y );
    void show ( );
}                                         http://www.java2all.com
Implementing Interface



                   http://www.java2all.com
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 declared by the interface.

     The general form of a class that includes the
implements clause looks like this:

      Access-specifier class classname [extends
superclass] [implements interface, [, interface..]]
{ // class body }
                                             http://www.java2all.com
If a class implements from more than one
interface, names are separated by comma.

      If a class implements two interfaces that declare
the same method, then the same method will be used
by clients of either interface.

     The methods that implement an interface must
be declared as public.

      The type-signature of implementing method
must match exactly the type signature specified in the
interface.
                                             http://www.java2all.com
interface religion
{
   String city = new String("Amritsar");
   void greet();
   void pray();
}

class gs implements religion
{
   public void greet()
   {
     System.out.println("We greet - ABCD");
   }
   public void pray()
   {
     System.out.println("We pray at " + city + " XYZ ");
   }
}
class iface1                                         Output :
{
   public static void main(String args[])
   {
     gs sikh = new gs();                             We greet - ABCD
     sikh.greet();
     sikh.pray();
                                                     We pray at Amritsar XYZ
   }
}
                                                                    http://www.java2all.com
Implementing interface having common
function name
 interface i1
{
   void disp();
}
interface i2
{
   void disp();
}
 class c implements i1, i2
{
   public void disp()
   {
     System.out.println("This is display .. ");
   }
}                                                 Output :
 class iface7
{
   public static void main(String args[])
   {                                              This is display ..
     c cobj = new c();

        cobj.disp();
    }
}                                                                      http://www.java2all.com
Note :


      When implementing an interface method, it must
be declared as public. It is possible for classes that
implement interfaces to define additional members of
their own.




                                            http://www.java2all.com
Partial Implementation of Interface :

      If we want to implement an interface in a class
we have to implement all the methods defined in the
interface.

      But if a class implements an interface but does
not fully implement the method defined by that
interface, then that class must be declared as
abstract.


                                             http://www.java2all.com
interface i1
{
   void disp1();                                   Output :
   void disp2();
}
abstract class c1 implements i1
{                                                  This is display of 1
   public void disp1()
   {
                                                   This is display of 2
     System.out.println("This is display of 1");
   }
}
class c2 extends c1
{
   public void disp2()
   {
     System.out.println("This is display of 2");
   }
}
class iface
{
   public static void main(String args[])
   {
     c2 c2obj = new c2();
     c2obj.disp1();
     c2obj.disp2();
   }
}                                                                   http://www.java2all.com
Interface Variable



                     http://www.java2all.com
Accessing interface variable :


      One can declare variable as object references
that uses an interface rather than a class type.


      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.

                                             http://www.java2all.com
nterface AreaCal
{
  final double pi = 3.14;
  double areacalculation(double r);
}

class Circle implements AreaCal
{
   public double areacalculation(double r)
   {
     double ar;
     ar = pi*r*r;                              Output :
     return ar;
   }
}                                              Area of Circle is : 329.89625
class iface3
{
   public static void main(String args[])
   {
     double area;
     AreaCal ac = new Circle();
     area = ac.areacalculation(10.25);
     System.out.println("Area of Circle is : " + area);
   }
}

                                                                        http://www.java2all.com
Here variable ac is declared to be of the interface
type AreaCal,it was assigned an instance of circle.

     Although ac can be used to access the
reacalculation() method,it cannot access any other
members of the client class.

      An interface reference variable only has
knowledge of the method declared by its interface
declaration.


                                             http://www.java2all.com
Extending Interface



                      http://www.java2all.com
Extending interfaces :

      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
implementation of all methods defined within the
interface inheritance.

Note : Any class that implements an interface must
implement all methods defined by that interface,
including any that inherited from other interfaces.
                                              http://www.java2all.com
interface if1
{
   void dispi1();
}
interface if2 extends if1
{
   void dispi2();
}
class cls1 implements if2
                                                    Output :
{
   public void dispi1()
   {                                                This is display of i1
     System.out.println("This is display of i1");
   }                                                This is display of i2
   public void dispi2()
   {
     System.out.println("This is display of i2");
   }
}
public class Ext_iface
{
   public static void main(String args[])
   {
     cls1 c1obj = new cls1();

     c1obj.dispi1();
     c1obj.dispi2();
}}                                                              http://www.java2all.com
Multiple inheritance using interface..
class stu
{
   int rollno;
   String name = new String();
   int marks;
   stu(int r, String n, int m)
   {
     rollno = r;
     name = n;
     marks = m;
   }
}
interface i
{
   void display();
}
class studerived extends stu implements i
{
   studerived(int r, String n, int m)
   {
     super(r,n,m);
   }

                                            http://www.java2all.com
public void display()
  {
    System.out.println("Displaying student details .. ");
    System.out.println("Rollno = " + rollno);
    System.out.println("Name = " + name);
    System.out.println("Marks = " + marks);
  }
}

public class Multi_inhe_demo
{
  public static void main(String args[])
  {
    studerived obj = new studerived(1912, "Ram", 75);
    obj.display();
  }

}
                                        Output :

                                        Displaying student details ..
                                        Rollno = 1912
                                        Name = Ram
                                        Marks = 75
                                                                    http://www.java2all.com
We can make various forms of interface
implementation as below




                                     http://www.java2all.com
http://www.java2all.com

Contenu connexe

Tendances (20)

Java package
Java packageJava package
Java package
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Data types in java
Data types in javaData types in java
Data types in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Java Streams
Java StreamsJava Streams
Java Streams
 
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
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Inner class
Inner classInner class
Inner class
 

Similaire à Interface

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
 
Interface
InterfaceInterface
Interfacevvpadhu
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
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
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdfAdilAijaz3
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfTabassumMaktum
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptTabassumMaktum
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptTabassumMaktum
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploaddashpayal697
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 

Similaire à Interface (20)

21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Interface
InterfaceInterface
Interface
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
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
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
 
Interfaces
InterfacesInterfaces
Interfaces
 
Java interface
Java interfaceJava interface
Java interface
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdf
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .ppt
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .ppt
 
Interface
InterfaceInterface
Interface
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx upload
 
Inheritance
InheritanceInheritance
Inheritance
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Java Interface
Java InterfaceJava Interface
Java Interface
 
Interface in java
Interface in javaInterface in java
Interface in java
 

Plus de kamal kotecha

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 

Plus de kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Dernier

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Dernier (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Interface

  • 1. Chapter 8 Interface http://www.java2all.com
  • 2. Interface http://www.java2all.com
  • 3. Interfaces are similar to abstract classes, but differ in their functionality. In interfaces, none of the methods are implemented means interfaces defines methods without body. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. But, it can contain final variables, which must be initialized with values. http://www.java2all.com
  • 4. Once it is defined, any number of classes can implement an interface. One class can implement any number of interfaces If we are implementing an interface in a class we must implement all the methods defined in the interface as well as a class can also implement its own methods. Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in C+ +. http://www.java2all.com
  • 5. Defining Interface http://www.java2all.com
  • 6. Syntax : [Access-specifier] interface interface-name { Access-specifier return-type method- name(parameter-list); final type var1=value; } http://www.java2all.com
  • 7. Where, Access-specifier is either public or it is not given. When no access specifier is used, it results into default access specifier and if interface has default access specifier then it is only available to other members of the same package. When it is declared as public, the interface can be used by any other code of other package.         Interface-Name: name of an interface, it can be  any valid identifier.  http://www.java2all.com
  • 8. Any class that includes an interface must implement all of the methods. Variables can be declared inside interface declarations. They are implicitly final and static, means they can not be changed by implementing it in a class. They must also be initialized with a constant value. http://www.java2all.com
  • 9. EX : interface Item { static final int code = 100; static final String name = "Fan"; void display ( ); } interface Area { static final float pi = 3.14F; float compute ( float x, float y ); void show ( ); } http://www.java2all.com
  • 10. Implementing Interface http://www.java2all.com
  • 11. 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 declared by the interface. The general form of a class that includes the implements clause looks like this: Access-specifier class classname [extends superclass] [implements interface, [, interface..]] { // class body } http://www.java2all.com
  • 12. If a class implements from more than one interface, names are separated by comma. If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. The methods that implement an interface must be declared as public. The type-signature of implementing method must match exactly the type signature specified in the interface. http://www.java2all.com
  • 13. interface religion { String city = new String("Amritsar"); void greet(); void pray(); } class gs implements religion { public void greet() { System.out.println("We greet - ABCD"); } public void pray() { System.out.println("We pray at " + city + " XYZ "); } } class iface1 Output : { public static void main(String args[]) { gs sikh = new gs(); We greet - ABCD sikh.greet(); sikh.pray(); We pray at Amritsar XYZ } } http://www.java2all.com
  • 14. Implementing interface having common function name interface i1 { void disp(); } interface i2 { void disp(); } class c implements i1, i2 { public void disp() { System.out.println("This is display .. "); } } Output : class iface7 { public static void main(String args[]) { This is display .. c cobj = new c(); cobj.disp(); } } http://www.java2all.com
  • 15. Note : When implementing an interface method, it must be declared as public. It is possible for classes that implement interfaces to define additional members of their own. http://www.java2all.com
  • 16. Partial Implementation of Interface : If we want to implement an interface in a class we have to implement all the methods defined in the interface. But if a class implements an interface but does not fully implement the method defined by that interface, then that class must be declared as abstract. http://www.java2all.com
  • 17. interface i1 { void disp1(); Output : void disp2(); } abstract class c1 implements i1 { This is display of 1 public void disp1() { This is display of 2 System.out.println("This is display of 1"); } } class c2 extends c1 { public void disp2() { System.out.println("This is display of 2"); } } class iface { public static void main(String args[]) { c2 c2obj = new c2(); c2obj.disp1(); c2obj.disp2(); } } http://www.java2all.com
  • 18. Interface Variable http://www.java2all.com
  • 19. Accessing interface variable : One can declare variable as object references that uses an interface rather than a class type. 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. http://www.java2all.com
  • 20. nterface AreaCal { final double pi = 3.14; double areacalculation(double r); } class Circle implements AreaCal { public double areacalculation(double r) { double ar; ar = pi*r*r; Output : return ar; } } Area of Circle is : 329.89625 class iface3 { public static void main(String args[]) { double area; AreaCal ac = new Circle(); area = ac.areacalculation(10.25); System.out.println("Area of Circle is : " + area); } } http://www.java2all.com
  • 21. Here variable ac is declared to be of the interface type AreaCal,it was assigned an instance of circle. Although ac can be used to access the reacalculation() method,it cannot access any other members of the client class. An interface reference variable only has knowledge of the method declared by its interface declaration. http://www.java2all.com
  • 22. Extending Interface http://www.java2all.com
  • 23. Extending interfaces : 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 implementation of all methods defined within the interface inheritance. Note : Any class that implements an interface must implement all methods defined by that interface, including any that inherited from other interfaces. http://www.java2all.com
  • 24. interface if1 { void dispi1(); } interface if2 extends if1 { void dispi2(); } class cls1 implements if2 Output : { public void dispi1() { This is display of i1 System.out.println("This is display of i1"); } This is display of i2 public void dispi2() { System.out.println("This is display of i2"); } } public class Ext_iface { public static void main(String args[]) { cls1 c1obj = new cls1(); c1obj.dispi1(); c1obj.dispi2(); }} http://www.java2all.com
  • 25. Multiple inheritance using interface.. class stu { int rollno; String name = new String(); int marks; stu(int r, String n, int m) { rollno = r; name = n; marks = m; } } interface i { void display(); } class studerived extends stu implements i { studerived(int r, String n, int m) { super(r,n,m); } http://www.java2all.com
  • 26. public void display() { System.out.println("Displaying student details .. "); System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); System.out.println("Marks = " + marks); } } public class Multi_inhe_demo { public static void main(String args[]) { studerived obj = new studerived(1912, "Ram", 75); obj.display(); } } Output : Displaying student details .. Rollno = 1912 Name = Ram Marks = 75 http://www.java2all.com
  • 27. We can make various forms of interface implementation as below http://www.java2all.com

Notes de l'éditeur

  1. White Space Characters
  2. White Space Characters
  3. White Space Characters