从另一个类访问时,不会执行java方法函数
我正在学习Java,并编写了以下代码:
public class Funcionario {
String nome;
String cpf;
String rg;
String dataEntrada;
String dept;
double salario;
double ganhoAnual;
int mesesEmpresa;
public static void main(String[] args) {
Funcionario f1 = new Funcionario();
f1.nome = "Sandra";
f1.salario = 1500;
f1.mesesEmpresa = 36;
f1.recebeAumento(150);
f1.cpf = "428.768.841-10";
f1.rg = "49.757.501-6";
f1.dataEntrada = "12 dez 2006";
f1.mostra();
}
void nome() {
System.out.println("Funcionario(a): " + nome);
}
void data() {
System.out.println("Data de Entrada: " + dataEntrada);
}
void recebeAumento(double aumento) {
salario = salario + aumento;
}
double calculaGanhoAnual() {
ganhoAnual = salario * 12;
return ganhoAnual;
}
void rgEcpf() {
System.out.println("CPF: " + cpf);
System.out.println("RG: " + rg);
}
void tempoEmpresa() {
if (mesesEmpresa % 12 == 0) {
System.out.println("Tempo de casa: " + mesesEmpresa / 12 + " ano(s)");
} else {
int mesesTempo = mesesEmpresa % 12;
int anosTempo = Math.round(mesesEmpresa / 12);
System.out.println("Tempo de casa: " + anosTempo + " ano(s) e " + mesesTempo + " mes(es)");
}
}
void mostra() {
this.nome();
System.out.println("Salario atual: " + this.salario);
System.out.println("Ganho anual: " + this.calculaGanhoAnual());
this.rgEcpf();
this.tempoEmpresa();
this.data();
}
}
class Empresa {
// is this an array? then why doesn't it have the type, like int[] or long[]?
Funcionario[] empregados;
String cnpj;
String nomeEmpresa;
private int contador = 0;
public int getContador() {
return this.contador;
}
// what happens in between the parentheses?
void adiciona(Funcionario f) {
if (contador <= 10) {
this.empregados[contador] = f;
this.contador++;
} else {
System.out.println("Array cheio!");
}
}
void mostraEmpregados() {
for (int i = 0; i < this.empregados.length; i++) {
System.out.println("Funcionario na posicao: " + i);
}
}
}
class TestaEmpresa {
// why does the reference to Empresa and Funcionario array have to be inside main? Otherwise, it gives <identifier> expected error
public static void main(String[] args) {
Empresa empresa = new Empresa();
// what is happening in the next line, exactly?
empresa.empregados = new Funcionario[10];
double salarioModificado = empresa.getContador() * 1500;
Funcionario f2 = new Funcionario();
f2.salario = salarioModificado;
empresa.adiciona(f2);
Funcionario f3 = new Funcionario();
f3.salario = salarioModificado * 2;
empresa.adiciona(f3);
empresa.mostraEmpregados();
}
}
但是,当我在TestaEmpresa
类中调用empresa.mostraEmpregados();
时,Empresa
类中的void mostraEmpregados() {}
将不会运行。因此,输出仅为:
Funcionario(a): Sandra
Salario atual: 1650.0
Ganho anual: 19800.0
CPF: 428.768.841-10
RG: 49.757.501-6
Tempo de casa: 3 ano(s)
Data de Entrada: 12 dez 2006
我知道我们需要类的引用,以便使用它们的属性或方法,但我无法实现这一点。你们能帮帮我吗
附言:请忽略^{
# 1 楼答案
你有两个主要的方法:在你的类上有一个
Funcionario
。运行此命令将生成您得到的输出:你们班还有一个
TestaEmpresa
。运行此命令将生成以下输出:所以,检查你的跑步配置。看起来您是在
Funcionario
上运行main方法,而不是在TestaEmpresa
上运行main方法