2013/04/17

Java - Capitulo 16: Sobrecarga de métodos

new Comment();

Capitulo 16: Sobrecarga de métodos

Java permite que vários métodos com o mesmo nome sejam definidos, contanto que esses métodos tenham conjuntos diferentes de parâmetros. Esse recurso é chamado de sobrecarga de métodos. Quando se chama um método sobrecarregado, o compilador Java seleciona o método adequado examinando a quantidade, os tipos e a ordem dos argumentos na chamada. A sobrecarga de métodos é comumente utilizada para criar vários métodos com o mesmo nome que realizam tarefas semelhantes, mas sobre tipos de dados diferentes.

Exemplo claro de uso de sobrecarga de métodos

//CONTAINER QUE VAI CONTER A INFORMAÇÃO
import java.awt.Container;
//JApplet PARA USO DO MESMO E JTextArea PARA PODER CRIAR AREAS DE TEXTO
import javax.swing.JApplet;
import javax.swing.JTextArea;
//CRIAMOS A CLASSE COM NOME "TWO" E HERDAMOS DA CLASSE Japplet
public class two extends JApplet {
 public void init() {
  JTextArea outArea = new JTextArea();
  Container container = getContentPane();
  container.add(outArea);
  outArea.setText("Integers values: " + square(6) + "\n Decimal values: "
    + square(6.6));
 }

 public int square(int intValue) {
  System.out.println("Decimal values result is:" + intValue);
  return intValue * intValue;
 }

 public double square(double doubleValue) {
  System.out.println("Integers values result ir:" + doubleValue);
  return doubleValue * doubleValue;
 }
}
public void init() {
   Called by the browser or applet viewer to inform this applet That it has been loaded into the system.

JTextArea outArea = new JTextArea();
   A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java.awt.TextArea class where it can reasonably do so. You can find information and examples of using all the text components in Using Text Components, a section in The Java Tutorial.


Container container = getContentPane();

   A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).

A sobrecarga de métodos acontece aqui:

public int square(int intValue) {
...
}


public double square(double doubleValue) {
...
}


Na linha 12:

outArea.setText("Integers values: " + square(6) + "\n Decimal values: "+ square(6.6));

Estamos chamando a função square passando como parametro 6 e 6.6, é nesse ponto onde a sobrecarga de métodos entra em ação!

Ele pega o valor 6 e procura o método square, ele perceve que tem dois métodos com o mesmo nome, a única diferença é que um é de tipo int e outro de tipo double, ele escolhe o int, no segundo parâmetro estamos passando 6.6 (um valor decimal), ele faz a mesma coisa, procura o método square, ele escolhe o mais apropriado, nesse casso escolhe o segundo que é do tipo decimal (double)

If You Enjoyed This, Take 5 Seconds To Share It

0 comentarios:

Postar um comentário