我想将一些多态性示例从书中分成几个文件,但在创建Programmer和Manager类的对象emp1和emp2时,主类PoliWithClasses出错。请让我知道运行以下代码有什么问题
文件Employee.java
package po;
abstract class Employee {
public void reachOffice() {
System.out.println("reached Office - India");
}
public abstract void startProject();
}
File Programmer.java
package po;
class Programmer extends Employee {
public void startProject(){
defineClasses();
unitTestCode();
}
private void defineClasses() {System.out.println("define classes");}
private void unitTestCode() {System.out.println("unit Test Code");}
}
文件管理器.java
package po;
class Manager extends Employee {
public void startProject() {
meetingWithCustomer();
defineProjectSchedule();
assignRespToTeam();
};
private void meetingWithCustomer() {System.out.println("meet Customer");}
private void defineProjectSchedule() {System.out.println("define Project Schedule");}
private void assignRespToTeam() {System.out.println("assign Resp To Team");}
}
文件PoliWithClasses.java
package po;
public class PoliWithClasses {
public static void main(String arg[]) {
}
Employee emp1=new Programmer();
Employee emp2=new Manager();
emp1.reachOffice();
emp2.reachOffice();
emp1.startProjectWork();
emp2.startProjectWork();
}
谢谢,我已经纠正了错字,但看起来这些对象在主类中看不到:
emp1.reachOffice();
emp2.reachOffice();
emp1.startProject();
emp2.startProject();
答案 0 :(得分:1)
您对给定错误消息的评论表明这是实际问题:
public class PoliWithClasses {
public static void main(String arg[]) {
//} <-- your bracket was here
Employee emp1=new Programmer();
Employee emp2=new Manager();
emp1.reachOffice();
emp2.reachOffice();
emp1.startProject(); // use consistent names
emp2.startProject();
} // the code must be contained in the method
}
总结一下:
startProject
的方法原型与Employee
中的方法原型匹配。main
的范围内。 emp1
和emp2
的声明被解释为包范围的字段声明。但是,emp1.reachOffice()
和emp2.reachOffice()
在方法实现之外都是非法的。我还将添加一个建议:每次在子类中重写方法时都使用@Override注释(它确保发生覆盖)。例如,在Programmer
班级中:
class Programmer extends Employee {
@Override
public void startProject(){
defineClasses();
unitTestCode();
}
// ...
}
答案 1 :(得分:0)
你的代码有误。不:
emp1.startProjectWork();
emp2.startProjectWork();
但:
emp1.startProject();
emp2.startProject();