Interface
Interface
looks like a class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by
default abstract (only method signature, no body, see: Java abstract method). Also, the variables
declared in an interface are public, static & final by default. We will
cover this in detail, later in this guide.
What
is the use of interface in Java?
As mentioned
above they are used for full abstraction. Since methods in interfaces do not
have body, they have to be implemented by the class before you can access them.
The class that implements interface must implement all the methods of that
interface. Also, java programming language does not allow you to extend more
than one class, However you can implement more than one interfaces in your
class.
Syntax:
Interfaces are declared by specifying a keyword “interface”. E.g.:
interface
interface_name
{
/* All the methods are public abstract by
default
* As you see they have no body
*/
public void method1();
public void method2();
}
Example
interface Bkec
{
public void show();
}
class cse implements bkec
{
public void show()
{
System.out.println("welcome to cse");
}
public static void main(String arg[])
{
bkec obj = new cse();
obj.show();
}
}
Output:
Welcome to cse
Interfaces are declared by specifying a keyword “interface”. E.g.:
Rules for using
Interface
·
Methods inside Interface must not
be static, final, native or strictfp.
·
All variables declared inside
interface are implicitly public static final variables(constants).
·
All methods declared inside Java
Interfaces are implicitly public and abstract, even if you don't use public or
abstract keyword.
·
Interface can extend one or more
other interface.
·
Interface cannot implement a class.
·
Interface can be nested inside
another interface.
Multiple
inheritance & interface
interface cse{
void print();
}
interface bkec{
void show();
}
class bet implements cse,bkec
{
public void print()
{
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}
public static void main(String args[]){
bet obj = new bet();
obj.print();
obj.show();
}
Output: Hello
Welcome
Next Topics
No comments:
Post a Comment