Sei sulla pagina 1di 37

Java Interfaces

Similar to a class definition Used mainly for function prototypes


Abstract method declarations Public and abstract by default!

Can also include:


constants (public static finals)

Interfaces
Using interface you can fully abstract a class interface from its implementation. Using interface, you can specify what a class must do, but not how it does them. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.

Interfaces
Java does not support the inheritance of multiple super classes into a single sub class. You can only specify one super class for any subclass that you create. To realize multiple inheritance in Java, interfaces are used.

Interfaces
One class can implement any number of interfaces. To implement an interface, a class must create the complete set of methods defined by the interface. Each class is free to determine the details of its own implementation.

Interfaces
//define an integer stack interface Interface IntStack { // store an item void push(int item); //retrieve an item int pop(); }

Interfaces
Access specifier of an interface is either public or not specified. If access specifier is not specified, it is considered to be default, which is package. Each class that implements an interface must implement all of the methods.

Partial Implementation
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 MyStack implements IntStack{ abstract void push(int item); int pop() { System.out.println(in pop..); } }

Interfaces
class FixedStack implements IntStack { private int stck[]; private int tos; public void push(int item){ System.out.println(In push); } public int pop(){ System.out.println(In pop); } }

Interfaces
When you implement an interface method, it must be declared as public. Interface reference variables can be used to refer to objects of class type that implement the interface. An interface reference variable only has the knowledge of the methods declared by its interface declaration.

Advantage of Interfaces
(over inheritance)

Any class can implements the interface (i.e., provides the contracts functionality) can be used Not constrained by sub classing

Interface Inheritance
A commitment to implement a contract No implementation is inherited Disadvantage:
No code sharing

Advantage:
No code commitment Freedom to implement any way you want

Variables in Interfaces
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. This concept is used to import shared constants into multiple classes by declaring an interface that contains variables initialized to a desired value.

Extending Interfaces
One interface can inherit another by the use of the keyword extends.

The net result is just the union of all the method specifications
When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.

Extending Interfaces
interface A { void test(); } interface B extends A { void test1(); }

Extending Interfaces
class inter implements B { public void test(){ System.out.println("in test"); } public void test1(){ System.out.println("in test1"); } public static void main(String args[]){ inter a = new inter(); a.test(); a.test1(); }

Interfaces vs. Abstract Classes


Use Abstract Classes when there is some implementation to share In C++, an abstract class with only pure virtual functions and no implementation behaves as an interface

Why Polymorphism
Many implementations and common Interface

Interfaces in the Java Library


Comparable: public int compareTo(Object x) Like Cs strcmp, returns:
Negative, if this < x Zero if this.equals(x) Positive, if this > x

You decide how the ordering works Used throughout the library

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;}}

Int Caltotalsal(emp * e[3]) { totsal=0; For(i=0;i<3;i++) { totsal+=e[i]->calyearlysal(); } 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); }

What If the classes cannot be related by inheritance hierarchy??

public interface Measurable{ double getMeasure(); }

Object Class All other classes are subclasses of Object class The 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.

Example
Print (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); }

Comparing Fractions

a c b d ad

bc

(b > 0, d > 0)
compareTo( ) should return ad - bc

Interfaces in the Java Library


Cloneable
For copying objects

Serializable
For automatic object storage and retrieval

Collection
Basic contract for collections

Abstract classes
Suppose it is required to create a super class that only defines a generalized form that will be shared by all of its sub-classes, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. This can be done by creating abstract classes containing abstract methods.

Abstract classes
An abstract class cannot be directly instantiated with the new operator. Any subclass of an abstract class must either implement all of the abstract methods in the super class or be itself declared abstract.

Abstract classes
abstract class Figure{ abstract double area(); void exist(){ System.out.println(Figure exist); } } class Rectangle extends Figure { double area() { System.out.println(Area Calculate here); } }

Abstract classes
Abstract classes can consist of methods that are not abstract. A sub-class that does not implement all the abstract methods of its super class, will be abstract. Abstract classes can be used to create object references.

Abstract classes
abstract class Figure{ double dim1; double dim2; Figure(double a, double b){ dim1 = a; dim2 = b; } abstract double area(); }

Abstract classes
class Rectangle extends Figure { Rectangle(double a, double b) { super(a,b) } double area() { System.out.println(Inside rectangle); return (dim1 * dim2); } }

Abstract classes
class AbstractDemo { public static void main(String args[]) { //Figure f = new Figure(10,10); Rectangle r = new Rectangle(9,6); Figure figref; //reference, no object created figref = r;
System.out.println(Area is+figref.area());

} }

Potrebbero piacerti anche