2020-05-09

Object类实验

  1. 理解Object中的 toString( ) 、equals( )方法;
  2. 学会instanceof关键字,学会自定义类时,toString ()、equals()方法的覆盖;
  3. 理解抽象类和接口的概念;
  4. 掌握抽象类、接口的定义和使用;
  5. 已给定一个类Shape和一个接口Showable。
    请按要求创建一个矩形(Rectangle)类,并且该类继承Shape,实现Showable接口:
    类成员如下.
    成员变量包括:
    颜色(color)
    长度(length)
    宽度(width)
    构造方法自主定义。
    普通方法:
    1、重写Object的toString()方法,返回字符串格式为:
    Rectangle[ 长度=???,宽度=???]
    2、覆盖Object类的equals方法,当且仅当当前颜色、长度和宽度均相等时,返回true,其他均为false。值
    3、实现抽象类和接口中相关的方法。
    在测试类的main方法中,创建对象,测试各部分功能。

Shape类

package birthday;
abstract class Shape{
	protected String color;
	public Shape(String s){
		this.color=s;
	}
	abstract double area();
	
}
interface Showable{
	abstract void showArea();  //显示面积
}

Rectangle 类

package birthday;

public class Rectangle extends Shape implements Showable {
String color;
double length;
double width;
public Rectangle (String color,double length,double width){
	super(color);
	this.length=length;
	this.width=width;
}
public String tostring(){
	return "Rectangle[ 长度="+length+"\t宽度="+width+"]";
}
public boolean equals(Object obj){
	if(this==obj){
		return true;
	}else if(obj instanceof Rectangle){
			Rectangle rectangle=(Rectangle)obj;
			return this.color==rectangle.color &&this.length==rectangle.length&&this.width==rectangle.width;
	}
	return false;
}
double area(){
	return width*length;
}
public void showArea(){
	System.out.println(area());
}
	
} 

测试类

package birthday;

public class Test {
	public static void main(String[] args) {
		
			Rectangle r1=new Rectangle("lanse",5.5,6.4);
			System.out.println(r1.toString());
			r1.showArea();
		}
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值