JAVAL Interfaces

Embed Size (px)

Citation preview

  • 8/4/2019 JAVAL Interfaces

    1/37

    Java InterfacesJava Interfaces

    Similar to a class definitionSimilar to a class definition

    Used mainly for function prototypesUsed mainly for function prototypes Abstract method declarationsAbstract method declarations

    Public and abstract by default!Public and abstract by default!

    Can also include:Can also include:

    constants (public static finals)constants (public static finals)

  • 8/4/2019 JAVAL Interfaces

    2/37

    InterfacesInterfaces

    Using interface you can fully abstract a classUsing interface you can fully abstract a class

    interface from its implementation.interface from its implementation.

    Using interface, you can specify what a classUsing interface, you can specify what a class

    must do, but not how it does them.must do, but not how it does them.

    Interfaces are syntactically similar to classes, butInterfaces are syntactically similar to classes, but

    they lack instance variables, and their methodsthey lack instance variables, and their methods

    are declared without any body.are declared without any body.

  • 8/4/2019 JAVAL Interfaces

    3/37

    InterfacesInterfaces

    Java does not support the inheritance of multipleJava does not support the inheritance of multiple

    super classes into a single sub class.super classes into a single sub class.

    You can only specify one super class for anyYou can only specify one super class for any

    subclass that you create.subclass that you create. To realize multiple inheritance in Java,To realize multiple inheritance in Java,

    interfaces are used.interfaces are used.

  • 8/4/2019 JAVAL Interfaces

    4/37

    InterfacesInterfaces

    One class can implement any number ofOne class can implement any number of

    interfaces.interfaces.

    To implement an interface, a class must createTo implement an interface, a class must create

    the complete set of methods defined by thethe complete set of methods defined by the

    interface.interface.

    Each class is free to determine the details of itsEach class is free to determine the details of its

    own implementation.own implementation.

  • 8/4/2019 JAVAL Interfaces

    5/37

    InterfacesInterfaces

    //define an integer stack interface//define an integer stack interface

    InterfaceInterface IntStackIntStack {{// store an item// store an item

    voidvoidpush(intpush(int item);item);

    //retrieve an item//retrieve an item

    intintpop();pop();

    }}

  • 8/4/2019 JAVAL Interfaces

    6/37

    InterfacesInterfaces

    Access specifier of an interface is eitherAccess specifier of an interface is either

    publicpublic or not specified.or not specified.

    If access specifier is not specified, it isIf access specifier is not specified, it is

    considered to be default, which isconsidered to be default, which ispackagepackage..

    Each class that implements an interfaceEach class that implements an interface

    must implement all of the methods.must implement all of the methods.

  • 8/4/2019 JAVAL Interfaces

    7/37

    Partial ImplementationPartial Implementation

    If a class includes an interface but does not fullyIf a class includes an interface but does not fully

    implement the methods defined by that interface,implement the methods defined by that interface,then that class must be declared asthen that class must be declared as abstractabstract..

    abstract class MyStack implements IntStack{

    abstract void push(int item);

    int pop() {

    System.out.println(in pop..);

    }

    }

  • 8/4/2019 JAVAL Interfaces

    8/37

    InterfacesInterfaces

    classclass FixedStackFixedStack implementsimplements IntStackIntStack {{

    privateprivate intint stckstck[];[];

    privateprivate intint tostos;;

    public voidpublic voidpush(intpush(int item){item){

    System.out.println(System.out.println(InInpushpush););

    }}

    publicpublic intintpop(){pop(){

    System.out.println(System.out.println(InInpoppop););

    }}

    }}

  • 8/4/2019 JAVAL Interfaces

    9/37

    InterfacesInterfaces

    When you implement an interface method, itWhen you implement an interface method, it

    must be declared asmust be declared aspublicpublic..

    Interface reference variables can be used toInterface reference variables can be used to

    refer to objects of class type that implement therefer to objects of class type that implement the

    interface.interface.

    An interface reference variable only has theAn interface reference variable only has the

    knowledge of the methods declared by itsknowledge of the methods declared by itsinterface declaration.interface declaration.

  • 8/4/2019 JAVAL Interfaces

    10/37

    Advantage of InterfacesAdvantage of Interfaces

    (over inheritance)(over inheritance)

    Any class can implements the interfaceAny class can implements the interface

    (i.e., provides the contract(i.e., provides the contracts functionality)s functionality)can be usedcan be used

    Not constrained by sub classingNot constrained by sub classing

  • 8/4/2019 JAVAL Interfaces

    11/37

    Interface InheritanceInterface Inheritance

    A commitment to implement a contractA commitment to implement a contract

    No implementation is inheritedNo implementation is inherited

    Disadvantage:Disadvantage:

    No code sharingNo code sharing

    Advantage:Advantage:

    No code commitmentNo code commitment Freedom to implement any way you wantFreedom to implement any way you want

  • 8/4/2019 JAVAL Interfaces

    12/37

    Variables in InterfacesVariables in Interfaces

    Variables can be declared inside of interfaceVariables can be declared inside of interface

    declarations.declarations.

    They are implicitlyThey are implicitly finalfinal andand staticstatic, meaning, meaning

    they cannot be changed by the implementingthey cannot be changed by the implementing

    class.class. They must also be initialized with a constantThey must also be initialized with a constant

    value.value.

    This concept is used to import shared constantsThis concept is used to import shared constantsinto multiple classes by declaring an interfaceinto multiple classes by declaring an interfacethat contains variables initialized to a desiredthat contains variables initialized to a desired

    value.value.

  • 8/4/2019 JAVAL Interfaces

    13/37

    Extending InterfacesExtending Interfaces

    One interface can inherit another by the use ofOne interface can inherit another by the use of

    the keywordthe keyword extendsextends.. The net result is just the union of all theThe net result is just the union of all the

    method specificationsmethod specifications

    When a class implements an interface thatWhen a class implements an interface that

    inherits another interface, it must provideinherits another interface, it must provide

    implementations for all methods defined withinimplementations for all methods defined withinthe interface inheritance chain.the interface inheritance chain.

  • 8/4/2019 JAVAL Interfaces

    14/37

    Extending InterfacesExtending Interfaces

    interface Ainterface A

    {{void test();void test();

    }}

    interface Binterface B extendsextendsAA

    {{

    void test1();void test1();

    }}

  • 8/4/2019 JAVAL Interfaces

    15/37

    Extending InterfacesExtending Interfaces

    class inter implements B {class inter implements B {

    public void test(){public void test(){

    System.out.println("inSystem.out.println("in test");test");

    }}

    public void test1(){public void test1(){

    System.out.println("inSystem.out.println("in test1");test1");

    }}

    public static void main(Stringpublic static void main(String argsargs[]){[]){

    inter a = new inter();inter a = new inter();

    a.test();a.test();

    a.test1();a.test1();

    }}

  • 8/4/2019 JAVAL Interfaces

    16/37

    Interfaces vs. Abstract ClassesInterfaces vs. Abstract Classes

    Use Abstract Classes when there is someUse Abstract Classes when there is some

    implementation to shareimplementation to share In C++, an abstract class with only pureIn C++, an abstract class with only pure

    virtual functions and no implementationvirtual functions and no implementationbehaves as an interfacebehaves as an interface

  • 8/4/2019 JAVAL Interfaces

    17/37

    Why PolymorphismWhy Polymorphism

    Many implementations and commonMany implementations and common

    InterfaceInterface

  • 8/4/2019 JAVAL Interfaces

    18/37

    Interfaces in the Java LibraryInterfaces in the Java Library

    ComparableComparable::

    publicpublic intint compareTo(ObjectcompareTo(Object x)x) Like CLike Css strcmpstrcmp, returns:, returns:

    Negative, if this < xNegative, if this < x Zero if this.equals(x)Zero if this.equals(x)

    Positive, if this > xPositive, if this > x

    You decide how the ordering worksYou decide how the ordering works

    Used throughout the libraryUsed throughout the library

  • 8/4/2019 JAVAL Interfaces

    19/37

    Employee {

    Empid

    fixed

    Virtual Calyearlysal(){return 12*fixed;}}

    Adhoc: public Employee {

    Wageperday

    No of days worked

    Calyearlysal(){

    return Employee::calyearlysal+(wagesperday*noofdays);}}

    Permanent emp :public employee{

    Yearlybonus

    calyearlysalary(){Return employee::calyearlysal+yearlybonus;}}

  • 8/4/2019 JAVAL Interfaces

    20/37

    Int Caltotalsal(emp * e[3])

    {

    totsal=0;

    For(i=0;icalyearlysal();}

    Return totsal;

    }

    Main()

    {Employee *e[3];

    e[0]=new employee(1,200);

    e[1]=new adhoc(1,200,22,300);

    e[2]= new permanent(1,200,4000);

    }

  • 8/4/2019 JAVAL Interfaces

    21/37

    What If the classes cannot be related

    by inheritance hierarchy??

  • 8/4/2019 JAVAL Interfaces

    22/37

  • 8/4/2019 JAVAL Interfaces

    23/37

  • 8/4/2019 JAVAL Interfaces

    24/37

  • 8/4/2019 JAVAL Interfaces

    25/37

    public interface Measurable{

    double getMeasure();}

  • 8/4/2019 JAVAL Interfaces

    26/37

  • 8/4/2019 JAVAL Interfaces

    27/37

    Object Class

    All other classes are subclasses of Object classThe reference variable of type Object can refer to an object of

    any other class.

    It defines the following methods

    Object clone()

    Boolean equals(Object obj);

    Class getClass();

    Int hashcode()

    String toString();

    Etc.

  • 8/4/2019 JAVAL Interfaces

    28/37

    ExampleExamplePrint (object x)

    {

    System.out.print(x);

    x.display();

    }

    Main(){

    Account a=new account(2,1000);

    student s=new student(1,abc);

    print(a);

    Print(s);

    }

  • 8/4/2019 JAVAL Interfaces

    29/37

    Comparing FractionsComparing Fractions

    ( 0, 0)

    a c

    b d

    ad bc

    b d

    > >

    compareTo( ) should return ad - bc

  • 8/4/2019 JAVAL Interfaces

    30/37

    Interfaces in the Java LibraryInterfaces in the Java Library

    CloneableCloneable

    For copying objectsFor copying objects

    SerializableSerializable

    For automatic object storage and retrievalFor automatic object storage and retrieval CollectionCollection

    Basic contract for collectionsBasic contract for collections

  • 8/4/2019 JAVAL Interfaces

    31/37

    Abstract classesAbstract classes

    Suppose it is required to create a super classSuppose it is required to create a super class

    that only defines a generalized form that will bethat only defines a generalized form that will beshared by all of its subshared by all of its sub--classes, leaving it toclasses, leaving it to

    each subclass to fill in the details.each subclass to fill in the details.

    Such a class determines the nature of theSuch a class determines the nature of the

    methods that the subclasses must implement.methods that the subclasses must implement.

    This can be done by creating abstract classesThis can be done by creating abstract classes

    containing abstract methods.containing abstract methods.

  • 8/4/2019 JAVAL Interfaces

    32/37

    Abstract classesAbstract classes

    An abstract class cannot be directly instantiatedAn abstract class cannot be directly instantiated

    with thewith the newnew operator.operator.

    Any subclass of an abstract class must eitherAny subclass of an abstract class must either

    implement all of the abstract methods in theimplement all of the abstract methods in thesuper class or be itself declared abstract.super class or be itself declared abstract.

  • 8/4/2019 JAVAL Interfaces

    33/37

    Abstract classesAbstract classes

    abstract class Figure{abstract class Figure{

    abstract double area();abstract double area();

    void exist(){void exist(){

    System.out.println(System.out.println(FigureFigure existexist); }); }

    }}

    class Rectangleclass Rectangle extendsextends Figure {Figure {

    double area() {double area() {

    System.out.println(System.out.println(AreaArea CalculateCalculateherehere););

    }}

    }}

  • 8/4/2019 JAVAL Interfaces

    34/37

    Abstract classesAbstract classes

    Abstract classes can consist of methodsAbstract classes can consist of methods

    that are not abstract.that are not abstract.

    A subA sub--class that does not implementclass that does not implement allall

    the abstract methods of its super class,the abstract methods of its super class,

    will be abstract.will be abstract.

    Abstract classes can be used to createAbstract classes can be used to create

    object references.object references.

  • 8/4/2019 JAVAL Interfaces

    35/37

    Abstract classesAbstract classes

    abstractabstract class Figure{class Figure{

    double dim1;double dim1;double dim2;double dim2;

    Figure(double a, double b){Figure(double a, double b){

    dim1 = a;dim1 = a;

    dim2 = b;dim2 = b;

    }}

    abstractabstract double area();double area();

    }}

  • 8/4/2019 JAVAL Interfaces

    36/37

    Abstract classesAbstract classes

    class Rectangleclass Rectangle extendsextends Figure {Figure {

    Rectangle(double a, double b) {Rectangle(double a, double b) {

    super(a,b)super(a,b)

    }}

    double area() {double area() {System.out.println(System.out.println(InsideInside rectanglerectangle););

    return (dim1 * dim2);return (dim1 * dim2);

    }}

    }}

  • 8/4/2019 JAVAL Interfaces

    37/37

    Abstract classesAbstract classes

    classclassAbstractDemoAbstractDemo {{

    public static void main(Stringpublic static void main(String argsargs[])[])

    {{

    //Figure f = new Figure(10,10);//Figure f = new Figure(10,10);

    Rectangle r = new Rectangle(9,6);Rectangle r = new Rectangle(9,6);

    FigureFigure figreffigref;;

    //reference, no object created//reference, no object created

    figreffigref = r;= r;

    System.out.println(System.out.println(AreaArea isis+figref.area+figref.area());());

    }}

    }}