面向对象------------练习(十三)

1.定义一个长方形类,定义 求周长和面积的方法,然后定义一个测试类进行测试。

分析:
        成员变量:
            宽width,高high
        空参有参构造
        成员方法:
            setXxx和getXxx
            求周长:getLength()
            求面积:getArea()
class Test1_Rectangle {						//Rectangle矩形
	public static void main(String[] args) {
		//第一种方式:使用构造方法赋值
		Rectangle r = new Rectangle(10,20);
		System.out.println(r.getLength());		//周长
		System.out.println(r.getArea());		//面积
		//第二种方式:使用set方法赋值
		Rectangle r2 = new Rectangle();
		r2.setWidth(10);
		r2.setHigh(20);
		System.out.println(r2.getLength());		//周长
		System.out.println(r2.getArea());		//面积
	}
}

class Rectangle {
	private int width;				//宽
	private int high;				//高

	public Rectangle(){}			        //空参构造

	public Rectangle(int width,int high) {
		this.width = width;			//有参构造
		this.high = high;
	}

	public void setWidth(int width) {//设置宽
		this.width = width;
	}

	public int getWidth() {			//获取宽
		return width;
	}

	public void setHigh(int high) {	//设置高
		this.high = high;
	}

	public int getHigh() {			//获取高
		return high;
	}

	public int getLength() {		//获取周长
		return 2 * (width + high);
	}

	public int getArea() {			//获取面积
		return width * high;
	}
}

2.定义一个员工类Employee

分析:

成员,然后给出成员变量
        * 姓名name,工号id,工资salary
    * 构造方法,
        * 空参和有参的
    * getXxx()setXxx()方法,
    * 以及一个显示所有成员信息的方法。并测试。
        * work

class Test2_Employee {						//employee员工
	public static void main(String[] args) {
		Employee e = new Employee("张三","9521",20000);
		e.work();
	}
}

class Employee {
	private String name;					//姓名
	private String id;					//工号
	private double salary;					//工资

	public Employee() {}					//空参构造

	public Employee(String name, String id, double salary) {//有参构造
		this.name = name;
		this.id = id;
		this.salary = salary;
	}

	public void setName(String name) {		//设置姓名
		this.name = name;
	}

	public String getName() {			//获取姓名
		return name;
	}

	public void setId(String id) {			//设置id
		this.id = id;
	}

	public String getId() {				//获取id
		return id;
	}

	public void setSalary(double salary) {	//设置工资
		this.salary = salary;
	}
	
	public double getSalary() {			//获取工资
		return salary;
	}

	public void work() {
		System.out.println("我的姓名是:" + name + ",我的工号是:" + id + ",我的工资是:" + salary 
			+ ",我的工作内容是java");
	}
}
	

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值