0% found this document useful (0 votes)
10 views5 pages

10 Interfaces

The document explains the concept of interfaces in Java, highlighting their role in abstracting class implementations and allowing multiple classes to implement the same interface. It covers defining interfaces, nested interfaces, shared constants, interface extension, and the introduction of default methods in JDK 8. Examples are provided to illustrate the implementation and usage of interfaces, demonstrating their flexibility and utility in Java programming.

Uploaded by

TARINI MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

10 Interfaces

The document explains the concept of interfaces in Java, highlighting their role in abstracting class implementations and allowing multiple classes to implement the same interface. It covers defining interfaces, nested interfaces, shared constants, interface extension, and the introduction of default methods in JDK 8. Examples are provided to illustrate the implementation and usage of interfaces, demonstrating their flexibility and utility in Java programming.

Uploaded by

TARINI MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Interfaces

i) Using the keyword interface, you can fully abstract a class’ interface from its
implementation. That is, using interface, you can specify what a class must do,
but not how it does it.
ii) Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
iii) In practice, this means that you can define interfaces that don’t make assumptions
about how they are implemented.
iv) Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.
v) To implement an interface, a class must create the complete set of methods
defined by the interface.
vi) However, each class is free to determine the details of its own implementation.
vii) By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism.
viii) Interfaces are designed to support dynamic method resolution at run time.
ix) Since, interfaces are in a different hierarchy from classes, it is possible for classes
that are unrelated in terms of the class hierarchy to implement the same interface.

Defining an Interface
An interface is defined much like a class. This is a simplified 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;
}

Example
interface Callback
{
void callback(int param);
}

class Client implements Callback


{
// Implement Callback's interface
//When you implement an interface method, it must be declared
as public.
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.");
}
}

class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}

Another implementation
interface Callback
{
void callback(int param);
}

// Another implementation of Callback.


class AnotherClient implements Callback
{
// Implement Callback's interface
//When you implement an interface method, it must be declared
as public.
public void callback(int p)
{
System.out.println("Another version of callback");
System.out.println("p squared is " + (p*p));
}
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}

Nested Interfaces
An interface can be declared a member of a class or another interface. Such an interface is
called a member interface or a nested interface.
A nested interface can be declared as public, private, or protected.
This differs from a top-level interface, which must either be declared as public or use the
default access level, as previously described.
When a nested interface is used outside of its enclosing scope, it must be qualified by the
name of the class or interface of which it is a member.

class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false: true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}

Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When you include
that interface in a class (that is, when you “implement” the interface), all of those variable
names will be in scope as constants. (This is similar to using a header file in C/C++ to create
a large number of #defined constants or const declarations.)
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 rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
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%
}
}
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;
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());
}
}

Interfaces Can Be Extended


interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Default Interface Methods


Prior to JDK 8, an interface could not define any implementation whatsoever. This meant that
for all previous versions of Java, the methods specified by an interface were abstract,
containing no body.
The release of JDK 8 has changed this by adding a new capability to interface called the
default method.

public interface MyIF {


// This is a "normal" interface method declaration.
// It does NOT define a default implementation.
int getNumber();
// This is a default method. Notice that it provides
// a default implementation.
default String getString() {
return "Default String";
}
}

// Implement MyIF.
class MyIFImp implements MyIF {
// Only getNumber() defined by MyIF needs to be implemented.
// getString() can be allowed to default.
public int getNumber() {
return 100;
}
}
// Use the default method.
class DefaultMethodDemo {

public static void main(String args[]) {


MyIFImp obj = new MyIFImp();
// Can call getNumber(), because it is explicitly
// implemented by MyIFImp:
System.out.println(obj.getNumber());
// Can also call getString(), because of default
// implementation:
System.out.println(obj.getString());
}
}
The output is shown here:
100
Default String

You might also like