方法的重载和重写的区别(续)

方法重写
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("输入有误!请重新输入");
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值