interface
- We can create interface by using interface keyword.
- Interface can contains,
- variables
- abstract methods
- sub class
- abstract methods will be implemented in sub class of interface.
- If sub class didn't provide the implementation for abstract method then we need to declare that sub class as abstract class.
- If any class extends this sub class then that sub class will provide the implementation for abstract methods.
- object creation is not possible for interface.
- Interface can not contain not even single method also, syntactically its valid.We can called as Marker interface.
Syntax
interface NameOfTheInterface
{
It can contains variables, abstract methods;
}
Example
interface BankService
{
int balance = 500; // by default this variable is public static final
public abstract int deposite(float money);
public abstract int deposite(float money);
}
Program : Example on interface
-------------------------------------------------------------------------------------
Program name : Employee.java
Output :
Employee added
Employee edited
interface EmpService
{
public abstract void add();
public abstract void edit();
}
class EmpServiceImpl implements EmpService
{
public void add()
{
System.out.println("Employee added");
}
public void edit()
{
System.out.println("Employee edited");
}
}
class Employee
{
public static void main(String args[])
{
EmpServiceImpl emp = new EmpServiceImpl ();
emp.add();
emp.edit();
}
}
Compile : javac Employee.java
Run : java Employee
Output :
Employee added
Employee edited
-------------------------------------------------------------------------------------
Program name : Student.java
Output :
Student Joined
Student Attending classes
Student preparing for exams, in a single day prepared 10 subjects
Student preparing for exams, in a single day prepared 10 subjects
interface StudentService
{
public abstract void join();
public abstract void attend();
public abstract void prepare();
public abstract void prepare();
}
abstract class StudentServiceImpl1 implements StudentService
{
public void join()
{
System.out.println("Student Joined");
}
public void attend()
{
System.out.println("Student Attending classes");
}
}
class StudentServiceImpl2 extends StudentServiceImpl1
{
public void prepare()
{
System.out.println("Student preparing for exams, in a single day prepared 10 subjects");
}
}
class Student
{
public static void main(String args[])
{
StudentServiceImpl2 std= new StudentServiceImpl2 ();
std.join();
std.attend();
std.prepare();
std.prepare();
}
}
Compile : javac Student.java
Run : java Student
Output :
Student Joined
Student Attending classes
Student preparing for exams, in a single day prepared 10 subjects
Student preparing for exams, in a single day prepared 10 subjects
-------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan