Cannot find symbol method - Mas o método existe na classe! <o>

5 respostas
S

Eu ainda não otimizei o código a seguir para fins de velocidade de execução, apenas estou desenvolvendo a idéia.
Então, é claro que haverá o que melhorar. Mas o erro que trago aqui me parece completamente estranho.

A classe mãe:

public class Entrevistado{
	protected String nome;
	protected char sexo;
	protected String eMail;
	
	
	
	
	//////////////////// *****MÉTODOS CONSTRUTORES*****
	////////////////////
	////////////////////
	
	public Entrevistado (String Nome,char Sexo, String NovoMail){
		
		setNome(Nome);
		setSexo(Sexo);
		setMail(NovoMail);
		
	}
	
	
	
	
	//////////////////// *****SET DO NOME, SEXO E MAIL*****
	////////////////////
	////////////////////
	
	void setNome (String novoNome){
		nome=novoNome;
		
	}
	
	void setSexo (char novoSexo){
		if (novoSexo=='m'){
			sexo='M';
		
		}
		
		else if (novoSexo=='f'){
			sexo='F';
		}
		
		else
		sexo=novoSexo;
		
	}
	
	void setMail (String novoMail){
		eMail=novoMail;
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//////////////////// *****GETS DO NOME, SEXO E MAIL*****
	////////////////////
	////////////////////
	
	String getNome (){
		return nome;
	}
	
	char getSexo (){
		return sexo;
	}
	
	String getMail (){
		return eMail;
	}
	
	
	//////////////////// *****DEFINIÇÃO DE toString*****
	////////////////////
	////////////////////
	public String toString (){
		
		return "Nome: " + nome + "\nSexo: " + sexo + "\neMail: " + eMail;
	}
	
	
	
}//fim da classe Entrevistado

Acima, a classe mãe, certo? Abaixo, a classe herdada:

public class FuncionarioAdministrativo extends Entrevistado{
	protected String matricula;
	protected String setor;
	protected double salario;
	protected String cargo;
	
	
	public FuncionarioAdministrativo (String Nome,char Sexo, String NovoMail,String NovaMatricula, String NovoSetor, String NovoCargo, double NovoSalario){
		
		super (Nome,Sexo,NovoMail);
		setMatricula(NovaMatricula);
		setSetor(NovoSetor);
		setSalario(NovoSalario);
		setCargo(NovoCargo);
		
	}
	
	
	
	
    //////////////////// *****SET MATRÍCULA, SETOR, SALÁRIO E CARGO*****
	////////////////////
	////////////////////
	
	public void setMatricula (String novaMatricula){
		
		matricula = novaMatricula;
	
		
	}
	
	public void setSetor (String novoSetor){
		
		setor = novoSetor;
	
		
	}
	
	public void setSalario (double novoSalario){
		
		salario = novoSalario;
	
		
	}
	
	public void setCargo (String novoCargo){
		
		cargo = novoCargo;
	
		
	}
	
	
	
	
	
	
	
	
	
	//////////////////// *****GET MATRÍCULA, SETOR, SALÁRIO E CARGO*****
	////////////////////
	////////////////////
	
	
	
	public String getMatricula(){
		
		return matricula;
	}
	
	public String getSetor(){
		
		return setor;
	}
	
	public double getSalario(){
		
		return salario;
	}
	
	public String getCargo(){
		
		return cargo;
	}
	
	
	
	
	
	
	
	
	//////////////////// *****DEFINIÇÃO DE toString*****
	////////////////////
	////////////////////

	
		
	
	public String toString (){
		
		return super.toString() + "\n Matrícula: " + getMatricula()+ "\n Setor: " + getSetor() + "\n Salário: R$" + salario + "\nCargo: " + getCargo();
	}
	

	}

Compilado com sucesso.

Aí fiz uma main que dá opções ao usuário:

//package Entrevistado;
//package Aluno;
import java.util.Scanner;
import java.lang.String;

public class Programa {
	
		
	
	public static Entrevistado[] vetor = new Entrevistado [0];
	
	
	////////////////////// INSERINDO ENTREVISTADOS!
	
	
	static void inserirEntrevistados(){
		int opcao;
		Scanner input = new Scanner (System.in);
			do{
		System.out.println("Qual a categoria do entrevistado?\n  1 - Funcionário Administrativo\n  2 - Professor\n  3 - Aluno\n  4 - Pessoa da comunidade\n 5 - NÃO QUERO ADICIONAR MAIS!");
		opcao = input.nextInt();
		
		
		
		
		
	
		
		
		
		switch (opcao){
			
			
			
			
			
			case 1:
			 
			//FUNCIONÁRIO ADMINISTRATIVO
			
			System.out.println("VOCÊ ESTÁ ARMAZENANDO UM FUNCIONÁRIO ADMINISTRATIVO.\n Qual o nome do funcionário?");
			String ONome = input.next();
			
			System.out.println("Qual o sexo do entrevistado?\n 1 - Masculino\n 2 - Feminino");
			int verificar = input.nextInt();
			char OSexo;
			if (verificar==1){
				OSexo = 'M';		
			}
			
			else {
			
				OSexo = 'F';
			}
			
			System.out.println("Qual a matrícula do entrevistado?");
			String AMatricula = input.next();
			
			System.out.println("Em que setor o funcionário atua?");
			String OSetor = input.next();
			
			System.out.println("Qual o cargo ocupado pelo funcionário?");
			String OCargo = input.next();
			
			System.out.println("Qual o salário do funcionário? Entrar com valor em Reais.");
			float OSalario = input.nextFloat();
			
			System.out.println("Digite o e-mail do funcionário.");
			String OMail = input.next();
			
			FuncionarioAdministrativo funcionario = new FuncionarioAdministrativo (ONome, OSexo, OMail, AMatricula, OSetor, OCargo, OSalario);
			Entrevistado novoVetor[] = new Entrevistado [vetor.length+1];
			for (int i=0; i<vetor.length;i++){
				novoVetor[i] = vetor[i];
			}
			novoVetor[vetor.length]=funcionario;
			vetor = novoVetor;
			break;
			
		//FIM CASE 1
		
		
		
		
		
		
		
		
		
		case 2:
		
		// PROFESSOR
		System.out.println("VOCÊ ESTÁ ARMAZENANDO UM PROFESSOR.\n Qual o nome do professor?");
			String ONome2 = input.next();
			
			
		System.out.println("Qual o sexo do professor?\n 1 - Masculino\n 2 - Feminino");
			int verificar2 = input.nextInt();
			char OSexo2;
			if (verificar2==1){
				OSexo2 = 'M';		
			}
			
			else {
			
				OSexo2 = 'F';
			}
			
		
		System.out.println("Digite o e-mail do professor.");
			String OMail2 = input.next();
			
		System.out.println("Qual a matrícula do professor?");
			String AMatricula2 = input.next();
			
		System.out.println("Qual a carga horária semanal do professor? (valor em quantidade de horas)");
			int ACarga2 = input.nextInt();
			
		System.out.println("Qual o curso do professor?");
			String OCurso2 = input.next();
		
		System.out.println("Qual a escolaridade do professor?");
			String AEscolaridade2 = input.next();
			
		
		Professor novoProfessor = new Professor(ONome2, OSexo2, OMail2, AMatricula2, ACarga2, OCurso2, AEscolaridade2);
		Entrevistado novoVetor2[] = new Entrevistado [vetor.length+1];
			for (int i=0; i<vetor.length;i++){
				novoVetor2[i] = vetor[i];
			}
			novoVetor2[vetor.length]=novoProfessor;
			vetor = novoVetor2;	
			break;
			
	//FIM CASE 2
	
	
	
	
	
	
	
	
	
	
	case 3: // ALUNO
	
        System.out.println("VOCÊ ESTÁ ARMAZENANDO UM ALUNO.\n Qual o nome do aluno?");
			String ONome3 = input.next();
			
			
        System.out.println("Qual o sexo do aluno?\n 1 - Masculino\n 2 - Feminino");
			int verificar3 = input.nextInt();
			char OSexo3;
			if (verificar3==1){
				OSexo3 = 'M';		
			}
			
			else {
			
				OSexo3 = 'F';
			}
			
		
		System.out.println("Digite o e-mail do aluno.");
			String OMail3 = input.next();
			
		System.out.println("Qual a matrícula do aluno?");
			String AMatricula3 = input.next();
			
		System.out.println("Qual o curso do aluno?");
			String OCurso3 = input.next();
			
		System.out.println("Qual o período do aluno? (por extenso)");
			String OPeriodo3 = input.next();
			
		System.out.println("Entre com o CR do aluno.");
			double OCR3 = input.nextDouble();
			
		Aluno novoAluno = new Aluno(ONome3, OSexo3, OMail3, AMatricula3, OCurso3, OPeriodo3, OCR3);
		Entrevistado novoVetor3[] = new Entrevistado [vetor.length+1];
			for (int i=0; i<vetor.length;i++){
				novoVetor3[i] = vetor[i];
			}
			novoVetor3[vetor.length]=novoAluno;
			vetor = novoVetor3;	
			break;
			//FIM CASE 3
			
			
			
			
			
			
			
			case 4:
			
			
		
		// MEMBRO DA COMUNIDADE
		System.out.println("VOCÊ ESTÁ ARMAZENANDO UM MEMBRO DA COMUNIDADE.\n Qual o nome da pessoa?");
			String ONome4 = input.next();
			
			
        System.out.println("Qual o sexo da pessoa?\n 1 - Masculino\n 2 - Feminino");
			int verificar4 = input.nextInt();
			char OSexo4;
			if (verificar4==1){
				OSexo4 = 'M';		
			}
			
			else {
			
				OSexo4 = 'F';
			}
			
		
		System.out.println("Digite o e-mail da pessoa.");
			String OMail4 = input.next();
			
		System.out.println("Digite o CPF da pessoa.");
			String OCPF4 = input.next();
			
		System.out.println("Entre com a escolaridade da pessoa.");
			String AEscolaridade4 = input.next();
			
		System.out.println("A pessoa fez quantos cursos livres?");
			int CursosLivres4 = input.nextInt();


		Comunidade novoMembro = new Comunidade(ONome4, OSexo4, OMail4, OCPF4, AEscolaridade4, CursosLivres4);
		Entrevistado novoVetor4[] = new Entrevistado [vetor.length+1];
			for (int i=0; i<vetor.length;i++){
				novoVetor4[i] = vetor[i];
			}
			novoVetor4[vetor.length]=novoMembro;
			vetor = novoVetor4;	
			break;
			//FIM CASE 4
}
			
			
	
	}while (opcao!=5);
	
	
	
	
	
	}
	
	
	
	public static void listarEntrevistados(){
		
		if (vetor.length==0){
			System.out.println("Não há entrevistados cadastrados.");
		}
		
		else
		for (int i = 0; i<vetor.length; i++){
			
			System.out.println(vetor[i].toString());
		}
	}
	
	
	
	
	
	
	public static void listarEntrevistados(int Tipo){
		
		if (vetor.length==0){
			System.out.println("Não há entrevistados cadastrados.");
		}
		
		
		else
		
		switch (Tipo){
			
			
		case 1:
		
		
	        for (int i = 0; i<vetor.length; i++){
			
			if (vetor[i] instanceof FuncionarioAdministrativo)
				System.out.println(vetor[i].toString());
				
		}
		
		case 2:
	        for (int i = 0; i<vetor.length; i++){
			
			if (vetor[i] instanceof Professor)
				System.out.println(vetor[i].toString());		    
		    
		    
		
		}
		
		case 3:
		
	        for (int i = 0; i<vetor.length; i++){
			
			if (vetor[i] instanceof Aluno)
				System.out.println(vetor[i].toString());
				}
		
		
		case 4:
				
	        for (int i = 0; i<vetor.length; i++){
			
			if (vetor[i] instanceof Comunidade)
				System.out.println(vetor[i].toString());				
	}
	
	
	}
	
}
	
	
	
	
	
	
	public static void listarEntrevistados(double min, double max){
		double valorzim;
		
		if (vetor.length==0){
			System.out.println("Não há entrevistados cadastrados.");
		}
		
		
		else{
			
			
		
		for (int i = 0; i<vetor.length; i++){
			
			
			
			if (vetor[i] instanceof FuncionarioAdministrativo){
				valorzim = vetor[i].getSalario();
				if ((valorzim >= min) && (valorzim <= max)){
				
				vetor[i].toString();
				}
			}
		}
		
	}	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static void main (String[] args){
		
    
	    int usuario,usuario2=0;
	    String coisa = "";
	    
	    do{
	    
		Scanner input = new Scanner (System.in);
		
		
		
		
		
		
		
		
		
		
		
		
		System.out.println("\n\nOPÇÕES:\n\n\n\n   1 - Coletar dados de entrevistados\n   2 - Listar entrevistados por categoria\n   3 - Listar FUNCIONÁRIOS por faixa salarial\n   4 - Listar FUNCIONÁRIOS por SETOR\n   5 -  Listar DOUTORES com carga horária maior que 40 horas semanais e sua quantidade\n   6 - Listar membros da comunidade com cursos concluídos\n   7 - Listar entrevistas por sexo\n 8 - SAIR DO PROGRAMA");
		usuario = input.nextInt();
		switch (usuario){
			
			case 1:
			
			inserirEntrevistados();
			break;
			
			case 2:
			
			System.out.println("VOCÊ VAI LISTAR OS ENTREVISTADOS.\nEntre com a categoria desejada:\n 1 - Funcionário administrativo\n 2 - Professor\n 3 - Aluno\n 4 - Membro da comunidade");
			coisa = input.next();
			
			if (coisa.length() == 0){
			
			//	if (coisa == null || "".equals(coisa)) {
				listarEntrevistados();
			}
			else
			usuario2 = Integer.parseInt(coisa);
			
			listarEntrevistados(usuario2);
			break;
			
			case 3: 
			System.out.println("VOCÊ VAI LISTAR FUNCIONARIOS POR FAIXA SALARIAL.\n Qual o intervalo MÍNIMO?");
			double min = input.nextDouble();
			
			System.out.println("\n Qual o intervalo MÁXIMO?");
			double max = input.nextDouble();
			
			listarEntrevistados(min,max);
			break;
			
			
			
			
			
			
		}//FIM SWITCH
	

		
	
		
		}while (usuario!=8); //FIM MENU
		
		System.exit(0); //SAÍDA DO PROGRAMA
	}
	
	
	
	
	
	
	
	
	
}

Quando vou compilar, encontro o seguinte erro (ESTÁ NA LINHA 348: valorzim = vetor[i].getSalario(); ):

[size=18][color=red]cannot find symbol method getSalario()[/color][/size]

MAS COMO? Como vocês podem ver, isso está na classe FuncionarioAdministrativo.
Alguém enxerga o erro?

5 Respostas

V

Se você substituir a linha 348 pela escrita abaixo, funciona?

valorzim = ((FuncionarioAdministrativo)vetor[i]).getSalario();
S

Funcionou! Valeu, vinicius.

Mas o que estava faltando ali? Nem com o código correto eu entendi bem.

V

É porque a variável Entrevistado não tem o metódo getSalario(), que é algo especifico de uma classe filha dela. Para que possível a JVM conseguisse encontrar o metódo você teve que fazer com que ela voltasse a enxergar o objeto armazenado na variável como FuncionarioAdministrativo, fazendo o cast. Por isso que te falei para colocar aquele (FuncionarioAdministrativo) na frente do vetor, com o exemplo abaixo fica melhor de entender.

//Se não for feito o cast, não será possível acessar metodos especificos de FuncionarioAdministrativo
FuncionarioAdministrativo func = (FuncionarioAdministrativo) vetor[i];
valorzim = func.getSalario();
S

Entendido. Muito obrigado.

Por outro lado, surge-me outra dúvida, com a sua explicação:

Por que é necessário esse cast, se existe o instanceof antes (e, portanto, se ele verifica a posição i no vetor como sendo uma instância de FuncionarioAdministrativo)?

V

O instanceof serve para vc verificar se o objeto é do tipo ou subtipo de FuncionarioAdministrativo, só depois de verificar isso que você pode fazer o cast, segue um exemplo um pouco tosco abaixo, mas acho que vai servir para explicar.

/*Vamos supor que tenho um método setSalario, mas que por algum motivo resolvi deixar o parâmetro como sendo do tipo Object, quero o metodo só faça algo se o valor passado para o parâmetro for do tipo Integer, para detectar isso utilizo o instanceof, depois disso tenho que fazer o cast para conseguir acessar o método intValue da classe Integer, caso contrário só vou conseguir acessar aqueles métodos que forem comuns as classes Object e Integer, exemplo o método equals.*/ 

public void setSalario (Object valor) {
      if (valor instanceof Integer) {
            Integer temp = (Integer)valor;
            int s = temp.intValue();
      }
}

Espero ter ajudado… falow

Criado 14 de junho de 2008
Ultima resposta 15 de jun. de 2008
Respostas 5
Participantes 2