当前位置: 代码迷 >> Java相关 >> ,上面的程序错在那里
  详细解决方案

,上面的程序错在那里

热度:7808   发布时间:2013-02-25 21:44:09.0
求助,下面的程序错在那里
package interfaces;

public class TestClone {

 
public static void main(String[] args) {
House house1 = new House(1,1234);
House house2 = house1;
House house3 = (House)house1.clone();
  System.out.println(house1 == house2);
  System.out.println(house1.comparaTo(house2));
  System.out.println(house1 == house3);
  System.out.println(house1.comparaTo(house3));
}

}

class House implements Cloneable, Comparable {
private int id;
private double area;
private java.util.Date whenBuilt;

public House(int id,double area)
{
this.id = id;
this.area = area;
whenBuilt = new java.util.Date();
}

public int getId()
{
return id;
}

public double getArea()
{
return area;
}

public java.util.Date getWhenBuilt()
{
return whenBuilt;
}

public Object clone() throws CloneNotSupportedException
{
return super.clone();
}

public int comparaTo(Object o)
{
if(area > ((House)o).area)
return 1;
else if (area <((House)o).area)
return -1;
else return 0;
}
}



------解决方案--------------------------------------------------------
1 comparaTo 都得改成 compareTo
2 调用clone 方法,会抛出异常,要进行捕获或抛给上级调用者。
Java code
package interfaces;public class TestClone{    public static void main(String[] args) throws Exception     {        try        {            House house1 = new House(1,1234);            House house2 = house1;            House house3 = (House)house1.clone();            System.out.println(house1 == house2);            System.out.println(house1.compareTo(house2));        //campareTo not comparaTo            System.out.println(house1 == house3);            System.out.println(house1.compareTo(house3));        //campareTo not comparaTo        }        catch(CloneNotSupportedException e)                //捕获异常.        {            e.printStackTrace();        }    }}class House implements Cloneable, Comparable {    private int id;    private double area;    private java.util.Date whenBuilt;    public House(int id,double area)    {        this.id = id;        this.area = area;        whenBuilt = new java.util.Date();    }    public int getId()    {        return id;    }    public double getArea()    {        return area;    }    public java.util.Date getWhenBuilt()    {        return whenBuilt;    }    public Object clone() throws CloneNotSupportedException    {        return super.clone();    }    public int compareTo(Object o)                        //campareTo not comparaTo    {        if(area > ((House)o).area)        return 1;        else if (area <((House)o).area)        return -1;        else return 0;    }}
------解决方案--------------------------------------------------------
public static void main(String[] args) throws Exception ,这句不要抛出就可。
  相关解决方案