C
C
Core Java
Search…
24) Interfaces

Need of Interfaces:

Example:

Suppose we have two classes Programmer and Manager both of them extend some common feature from Employee class.Now let say we have the below requirement/behavior to implement

That's the reason why interface are needed

Code:

1
package com.gs.ilp.corejava.interfaces;
2
3
public interface Interviewer {
4
public void conductInterview();
5
}
Copied!
1
package com.gs.ilp.corejava.interfaces;
2
3
public interface Trainable {
4
public void attendTraining();
5
}
Copied!
1
package com.gs.ilp.corejava.interfaces;
2
3
public class Employeeee {
4
String name;
5
String address;
6
String phoneNumber;
7
String experience;
8
}
Copied!
1
package com.gs.ilp.corejava.interfaces;
2
3
public class Manager extends Employeeee implements Interviewer, Trainable {
4
int teamSize;
5
void reportProjectStatus() {
6
}
7
public void attendTraining() {
8
System.out.println("Mgr - attendTraining");
9
}
10
public void conductInterview() {
11
System.out.println("Mgr - conductInterview");
12
}
13
}
Copied!
1
package com.gs.ilp.corejava.interfaces;
2
3
public class Programmer extends Employeeee implements Trainable {
4
String[] programmingLanguages;
5
void writeCode() {
6
}
7
public void attendTraining() {
8
System.out.println("Prog - attendTraining");
9
}
10
}
Copied!
1
package com.gs.ilp.corejava.interfaces;
2
3
public class TestInterfaces {
4
public static void main(String[] args) {
5
Manager manager = new Manager();
6
manager.attendTraining();
7
manager.conductInterview();
8
9
Programmer programmer = new Programmer();
10
programmer.attendTraining();
11
}
12
}
Copied!

Output:

UML :

Defining Interfaces:

Types of methods in an interface :

Rules to implement Interface:

A class can implement multiple interfaces:

Rule 1:

Rule 2:

Multiple inheritance is possible using Interfaces:

Properties of a member of an interface:

Last modified 2yr ago