Interfaces em Java

Este post cobrirá as interfaces Java com exemplos – Um esforço para ajudá-lo a descobrir algo novo.

Interfaces Java

Quando se trata de interfaces Java , usar interfaces é outra técnica para realizar a abstração .

Uma “ classe totalmente abstrata ” chamada interface é usada para agrupar métodos relacionados com corpos vazios:

Exemplo

interface Bank{ // This is an interface of a Bank

    public void bank_name(); // This is an interface method contain no body
    public void bank_employees(); // Another empty body method is declared here
}

Example: 

1
2
3
4
5
6
7
8
9
10
interface Car{ // This is an interface of a Car
public void car_company(); // This is an interface method that does not contain a body
public void car_model(); // Another empty body method is declared here
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

A interface deve ser “implementada” (como herdada) por outra classe usando a palavra-chave implements (em vez de extends) para acessar as funções da interface.

Quando se trata de interfaces Java , a classe “implement” oferece o corpo do método da interface :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
interface SmartPhone{
public void camera(); // interface method is declared here
public void calling(String name); // another interface method is declared here
}
class SmartPhones_Applications implements SmartPhone{ // new class inherits from SmartPhone class using the implements keyword
public void camera(){ // Body of first interface method is declared here
System.out.println("Camera: 108 Megapixels (MP)");
}
public void calling(String name){ // Body of second interface method is declared here
System.out.println("Enter contact name to make a call : "+name);
}
}
public class Main {
public static void main(String[] args) {
SmartPhones_Applications my_object=new SmartPhones_Applications();
my_object.camera(); // Calling interface method 1
my_object.calling("Robert"); // calling interface method 2
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Outra abordagem.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interface Programming_languages{
public void java_founder();
public void java_developers();
}
class Java implements Programming_languages{
public void java_founder(){
System.out.println("Java was originally developed by James Gosling at Sun Microsystems");
}
public void java_developers() {
System.out.println("There are exactly 9,007,346+ Java developers in the world");
}
}
public class Main {
public static void main(String[] args) {
Java myobj=new Java();
myobj.java_founder();
myobj.java_developers();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Considerações sobre interfaces:

  1. Assim como as classes abstratas, uma interface não pode ser usada para construir objetos; por exemplo, no exemplo dado acima, um objeto “Programming_languages” não pode ser criado na Classe Principal.
  2. Os métodos de interface carecem de um corpo; em vez disso, a classe “implement” fornece um.
  3. Você deve substituir cada um dos métodos de uma interface ao implementá-la.
  4. Por padrão, os métodos de interface são públicos e abstratos.
  5. Por padrão, os atributos de interface public , static e final são usados.
  6. Um construtor é incompatível com uma interface (já que não é capaz de criar objetos).

Quando as interfaces devem ser usadas?

  • Para aumentar a segurança, oculte algumas informações e exiba apenas informações importantes sobre um objeto (interface).
  • A “herança múltipla” não é suportada pelo Java (uma classe só pode herdar de uma superclasse). No entanto, se se trata de interface Java , a classe pode implementar inúmeras interfaces, portanto, é alcançável com interfaces.

Lembrete: Use vírgulas para separar cada interface que deseja usar, para invocar várias interfaces (veja o exemplo abaixo).



Múltiplas Interfaces

Use uma vírgula para separar várias interfaces ao implementá-las:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
interface First_Interface{
public void first_Interface_Method();
}
interface Second_Interface{
public void second_Interface_Method();
}
class Third_Interface implements First_Interface,Second_Interface{
public void first_Interface_Method() {
System.out.println("This is my first Interface method");
}
public void second_Interface_Method() {
System.out.println("This is my second Interface method");
}
}
public class Main {
public static void main(String[] args) {
Third_Interface obj=new Third_Interface();
obj.first_Interface_Method();
obj.second_Interface_Method();
}
// Output 1: This is my first Interface method
// Output 2: This is my second Interface method
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Another Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
interface Interface1{
public void product(int mrx,int ample);
}
interface Interface2{
public void division(int mrx,int ample);
}
class Implementing_Class implements Interface1,Interface2{
public void product(int mrx,int ample){
System.out.println("Product of "+mrx+" x "+ample+" = "+(mrx*ample));
}
public void division(int mrx,int ample){
float result=(float)mrx/ample;
System.out.println("The Result of "+ mrx + " / "+ample+" is = "+result);
}
}
public class Main {
public static void main(String[] args) {
Implementing_Class my_object=new Implementing_Class();
my_object.product(12,8);
my_object.division(34,5);
}
// Output 1: Product of 12 x 8 = 96
// Output 2: The Result of 34 / 5 is = 6.8
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone