方法重写
1.在继承关系的子类中
2.重写的方法名、参数、返回值类型必须与父类相同
3.私有方法不能继承因而也无法重写
4.子类重写的方法不能比父类更严格(例如:父类的访问修饰符为protected,而子类只能是protected和public)
方法重载和方法重写的区别
方法重写的意义是实现多态
方法重写例子:
编写程序实现工作任务选择
问题描述:
编写程序,接收用户输入的信息,选择需要完成的工作任务。可供选
择的有:测试工作和编码工作
设定:
测试工作 属性:工作类型、工作名称、编写的测试用例个数、发现的Bug数量 方法:任务描述
编码工作 属性:工作类型、工作名称、有效编码行数、未解决的Bug个数 方法:任务描述
源代码参考:
工作类:Job.java
public class Job {
protected String style;
protected String name;
public Job(String style, String name) {
super();
this.style = style;
this.name = name;
}
public void introduce(){
System.out.println("工作名称:"+name+"\n工作类型:"+style);
}
}
测试工作类:TestJob.java
public class TestJob extends Job {
private int num;//编写用例个数
private int funbug;//发现bug数量
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getFunbug() {
return funbug;
}
public void setFunbug(int funbug) {
this.funbug = funbug;
}
public TestJob(String style, String name,int num,int funbug) {
super(style, name);
// TODO Auto-generated constructor stub
this.num = num;
this.funbug = funbug;
}
@Override
public void introduce() {
// TODO Auto-generated method stub
super.introduce();
System.out.println("编写用例个数:"+getNum()+"\n发现的Bug数量:"+getFunbug());
}
}
编码工作类:CodeJob.java
public class CodeJob extends Job {
private int sum;//有效编码的行数
private int wbug;//未解决的bug数
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public int getWbug() {
return wbug;
}
public void setWbug(int wbug) {
this.wbug = wbug;
}
public CodeJob(String style, String name,int sum,int wbug) {
super(style, name);
// TODO Auto-generated constructor stub
this.sum = sum;
this.wbug = wbug;
}
@Override
public void introduce() {
// TODO Auto-generated method stub
super.introduce();
System.out.println("有效编码行数:"+getSum()+"\n未解决的Bug个数:"+getWbug());
}
}
测试类:JobTest.java
public class JobTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("请选择要选择的工作(1.测试 2.编码):");
int n = sc.nextInt();
switch(n){
case 1:
TestJob tj = new TestJob("压力测试", "测试项目已经实现的功能", 20, 10);
tj.introduce();
return;
case 2:
CodeJob cj = new CodeJob("编码工作", "检查编码实现的功能", 15, 12);
cj.introduce();
return;
default:
System.out.println("输入有误!请重新输入");
}
}
}
}