-
Interfaces in Java
Hi
I am new to java and I want to clear the interface concept more clearly. Java is a great programming language. I like to code java programs. So, can any one help me in explaining interfaces in java, some interface examples will do. If you post some simple examples I can get it working by my side. hoping for a reply.
-
Re: Interfaces in Java
Interface is a group of related methods with empty bodies. Check this simple example you will be more clear with it. Every thing is explained in the code.
Code:
/*
Java Interface example.
This Java Interface example describes how interface is defined and
being used in Java language.
Syntax of defining java interface is,
<modifier> interface <interface-name>{
//members and methods()
}
*/
//declare an interface
interface IntExample{
/*
Syntax to declare method in java interface is,
<modifier> <return-type> methodName(<optional-parameters>);
IMPORTANT : Methods declared in the interface are implicitly public and abstract.
*/
public void sayHello();
}
}
/*
Classes are extended while interfaces are implemented.
To implement an interface use implements keyword.
IMPORTANT : A class can extend only one other class, while it
can implement n number of interfaces.
*/
public class JavaInterfaceExample implements IntExample{
/*
We have to define the method declared in implemented interface,
or else we have to declare the implementing class as abstract class.
*/
public void sayHello(){
System.out.println("Hello Visitor !");
}
public static void main(String args[]){
//create object of the class
JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
//invoke sayHello(), declared in IntExample interface.
javaInterfaceExample.sayHello();
}
}
/*
OUTPUT of the above given Java Interface example would be :
Hello Visitor !
*/
-
Re: Interfaces in Java
This is a simple example of Interface. The below example is like a syntax of interface, it explains how a basic interface looks like.
Code:
interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
-
Re: Interfaces in Java
In this class I implement Java shape interface in the circle class, up-casting for the object "circleshape". In Interfaces functions are public and abstract ,and fields are public and final. View the following example
Code:
public class Main {
public static void main(String[] args) {
shape circleshape=new circle();
circleshape.Draw();
}
}
interface shape
{
public String baseclass="shape";
public void Draw();
}
class circle implements shape
{
public void Draw() {
System.out.println("Drawing Circle here");
}
}
Page generated in 1,751,123,894.80337 seconds with 10 queries