Dear readers,
We already know that java does not support multiple Inheritance,But we
can achieve multiple inheritance using the concept called INTERFACE.
INTERFACE?
~~~~~~~~~
An interface in Java
is similar to a class, but the body of an interface can include only abstract
methods and final fields (constants). A class implements an
interface by providing code for each method declared by the interface.
SYNTAX:
~~~~~~~
access specifier interface
interfacename
{
abstract method();
}
Ex:
public interface Playable
{
void play();
}
ll the methods in an interface are assumed public and abstract. To
implement an interface, a class must do two things:
·
It must specify an implements clause on its class declaration.
·
It must provide an implementation for every method declared by the
interface.
Here’s a class that implements the Playable interface:
public class learnjava implements Playable
{
// additional fields and
methods go here
public void play()
{
// code that plays the game
goes here
}
// additional fields and
methods go here
}
Here, the declaration for the learnjava class
specifies implements Playable. Then the body of the class includes an
implementation of the play method.
A class can implement more than one interface:
Syntax for Implementing more than on Interface:
public class classname implements interfacename1,interfacename2
{
static final int code="1001"; //final variable declaration
abstract methods();
}
EX:
public class HeartsGame implements Playable, CardGame
{
// must implement methods of
the Playable
// and CardGame interfaces
}
NOTE:
1) An Interface must contain abstract function.
2)It must have only final variables
3)All the abstract method of a interface should be implemented in a
class.
No comments:
Post a Comment