Object类实验
- 理解Object中的 toString( ) 、equals( )方法;
- 学会instanceof关键字,学会自定义类时,toString ()、equals()方法的覆盖;
- 理解抽象类和接口的概念;
- 掌握抽象类、接口的定义和使用;
- 已给定一个类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();
}
}