我是java新手并创建一个小程序来清除核心java的基本原理。我正在创建员工基本信息和工资计数的程序。但是当我试图访问父变量以便我可以使用该变量并计算员工的工资时,我收到一条错误消息“empSalaryobj无法解析为变量”。
以下是我的Java代码,
class varEmployee {
int empId;
String empName;
final String empCompany = "Tata Consultancy Services";
int empSalary;
String empGender;
int empAge;
String empNationality;
}
class setEmployee extends varEmployee{
setEmployee(){
}
setEmployee(int empId){
this.empId=empId;
switch(empId){
case 1:
empName = "Aditya Batra";
empSalary = 10000;
empGender = "Male";
empAge = 26;
empNationality = "Indian";
break;
case 2:
empName = "Vishal Sharma";
empSalary = 20500;
empGender = "Male";
empAge = 26;
empNationality = "Australia";
break;
case 3:
empName = "Ashish Tiwari";
empSalary = 30000;
empGender = "Male";
empAge = 28;
empNationality = "Indian";
break;
case 4:
empName = "Mona Lisha";
empSalary = 40000;
empGender = "Female";
empAge = 24;
empNationality = "Oganda";
break;
default:
System.out.println("Invalid Employee ID");
}
}
}
class getEmployee extends setEmployee {
getEmployee(){
}
getEmployee(setEmployee obj){
int empIdobj = obj.empId;
String empNameobj = obj.empName;
int empSalaryobj = obj.empSalary;
String empGenderobj = obj.empGender;
int empAgeobj = obj.empAge;
String empNationalityobj = obj.empNationality;
System.out.println("Employee Id: "+empIdobj+"\nName: "
+empNameobj+"\nSalary: "+empSalaryobj
+"\nGender: "+empGenderobj+"\nAge: "
+empAgeobj+"\nNationality: "+empNationalityobj
+"\nCompany Name: "+empCompany);
}
}
class getEmployeeSalary extends getEmployee {
int empSalaryCaculation = empSalaryobj;
getEmployeeSalary(int empLeaves){
float empSal = (empSalaryCaculation/30)*(30-empLeaves);
System.out.println("Salary after leave deduction: "+empSal);
}
}
public class Employee {
public static void main(String[] args) {
setEmployee setobj=new setEmployee(1);
getEmployee getobj=new getEmployee(setobj);
getEmployeeSalary salobj=new getEmployeeSalary(5);
}
}
有人可以帮帮我吗。我也想知道为什么会出现此错误消息。
答案 0 :(得分:1)
empSalaryobj
是getEmployee
的构造函数中定义的局部变量。它不是getEmployeeSalary
的任何父类的字段,因此无法在getEmployeeSalary
的构造函数中访问它。
答案 1 :(得分:0)
你需要有一个getEmployeeSalary类的构造函数
getEmployeeSalary(int empLeaves,getEmployee employee)
{
float empSal = (employee.empSalaryobj/30)*(30-empLeaves);
System.out.println("Salary after leave deduction: "+empSal);
}
并且您不需要int empSalaryCaculation = empSalaryobj;
,因为您在getEmployeeSalary构造函数中直接实现它
你还需要让empSalary成为getEmployee类的数据字段
public class getEmployee extends varEmployee
{
public int empSalaryobj;
}
这里我使用Eric Allman压缩风格,因为它在任何辩论中都比K& R风格更好