Herança em Java

Estamos examinando a herança Java com exemplos, a fim de aprimorar o aprendizado.

O conceito de herança de Java é um dos pilares da Programação Orientada a Objetos.

Usamos herança Java quando existe um relacionamento Is-A entre os objetos.

Herança Java – Superclasse e Subclasse

Em Java, é possível que classes compartilhem características e métodos.

Quando se trata de herança Java , dividimos a “ideia de herança” em duas partes:

  1. A classe que herda de outra classe é conhecida como subclasse (Child Class).
  2. A classe que está sendo herdada é conhecida como superclasse (classe pai).

A palavra-chave extends pode ser usada para herdar de uma classe.

A linguagem Java (subclasse) no exemplo a seguir herda as propriedades e operações das linguagens de programação (superclasse):

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ProgrammingLanguages{ // Parent class is created here
void print_bio(){ // A no return type method is created in the Parent Class
System.out.println("Java is one of the most in-demand language!!");
}
} // Parent class ends here
class JavaLanguage extends ProgrammingLanguages{ // A child class is created here which extends from the parent class
public static void main(String[] args) { // Main Method
JavaLanguage my_object=new JavaLanguage(); // Creating an object of the child class in order to access the attributes and methods of the parent class
my_object.print_bio(); // Parent method calling from child class using object
}
// Output: Java is one of the most in-demand language!!
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Fruit{ // Here we have created the parent class
boolean isAppleTasty=true; // A boolean variable named as isAppleTasty is used here
}
class Apple extends Fruit{ // We created another class Apple and extended it from Fruit (Parent) class
public static void main(String[] args) {
Apple my_obj=new Apple(); // Object of Child class is created here
System.out.println("Is Apple tasty ?? : "+my_obj.isAppleTasty); // Printing the output by accessing parent attribute using object
}
// Output: Is Apple tasty ?? : true
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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
class Airplanes {
protected String founder_Boeing = "William Boeing"; // An attribute of class Airplanes
public void bio() { // A method of Aiplanes class
System.out.println("The first Airplane was founded by the Wright Brothers ");
}
}
class Boeing extends Airplanes{
private String model_number = "Boeing-737"; // Attribute with a private modifier from the Boeing x
public static void main(String[] args) {
// Create an object named as my_boeing
Boeing my_boeing= new Boeing();
// Invoke the method bio() from the Airplanes(Parent Class) by using an object
my_boeing.bio();
// We use here the remaining attributes from the Airplanes(Parent Class) and Boeing class (Child class)
System.out.println("The Founder of Boeing Airplane os : "+my_boeing.founder_Boeing);
System.out.println("The most famous Boeing plane is: "+my_boeing.model_number);
}
// Output 1: The first Airplane was founded by the Wright Brothers
// Output 2: The Founder of Boeing Airplane os : William Boeing
// Output 3: The most famous Boeing plane is: Boeing-737
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Você notou o modificador protegido na Classe Aviões?

Um modificador de acesso protegido foi aplicado ao atributofounder_boeing na classe Airplanes.

A classe Boeing não seria capaz de acessá-lo se fosse definido como privado .

Por que e quando usar “herança”?

– Facilita a reutilização de código: você pode reutilizar atributos e métodos de classes existentes ao criar novas classes.

Dica: veja o próximo capítulo, Polimorfismo , para ver um exemplo de métodos herdados sendo utilizados para realizar diferentes tarefas .



A palavra-chave final

Você pode empregar a palavra-chave final para evitar que outras classes herdem de uma classe.

Um erro de Java aparecerá se você tentar acessar uma classe final.

final class My_Final{

}
class My_Final_Child extends My_Final{
    
}

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
final class Football {
protected String footBall_founders = "The Chinese";
public void football_bio() {
System.out.println("Football/Soccer as a game ranks the first in the world");
}
}
class Footballer extends Football {
private String mrx_name = "Cristiano Ronaldo";
public static void main(String[] args) {
Footballer my_object= new Footballer();
my_object.football_bio();
System.out.println("Football founders: "+my_object.footBall_founders + "\nFamous Footballer: " + my_object.mrx_name);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Saída:

java: não pode herdar do futebol final

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
final class NFL {
protected String nfl_start_date = "October 3, 1920";
public void nfl_Into() {
System.out.println("The NFL was formed in 1920 as the American Professional Football Association (APFA) ");
}
}
class NFL_teams extends NFL {
private String [] nfl_team = {"1) Arizona Cardinals ","2) Baltimore Ravens ","3) Atlanta Falcons ","4) Buffalo Bills"};
public static void main(String[] args) {
NFL_teams my_object= new NFL_teams();
my_object.nfl_Into();
System.out.println("Football founders: "+my_object.nfl_start_date);
System.out.println("\nFive team names: \n");
for (int mrx=0;mrx<my_object.nfl_team.length;mrx++){
System.out.println(my_object.nfl_team[mrx]);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Saída:

java: não pode herdar da NFL final


Benefícios da Herança Java

  • O mecanismo de herança do Java é mais prático para a reutilização do código. Classes filhas podem operar diretamente o código na classe pai.
  • O mecanismo de herança em Java nos permite alcançar o polimorfismo.
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