1、关于类中的main方法
main方法的作用就是程序执行入口,任何类都可以有main方法,没有main方法无法开始执行。
现在有一段程序是这样的:
//Sheep01.class
public class Sheep01 implements Cloneable{
private Date date;
private String name;
public Sheep01(){
// TODO Auto-generated constructor stub
}
public Sheep01(Date date, String name) {
super();
this.date = date;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Demo01.class
public class Demo01 {
Sheep01 s1 = new Sheep01(new Date(), "hah");
Sheep01 s2 = (Sheep01) s1.clone();
}
这两个类文件中,Demo01.class文件中有编译错误:“Default constructor cannot handle exception type CloneNotSupportedException thrown by implicit super constructor. Must define an explicit constructor“,大概的意思就是说,默认的构造器不能处理CloneNotSupportedException这个异常,需要定义特定的构造器来处理。CloneNotSupportedException这个异常怎么出现的呢,因为clone()方法会抛出异常,在Demo01中的两句代码实际上是在定义两个成员变量,初始化类的时候要做的事情,而且s2在定义的过程中会抛出异常,所以需要特定的Demo01的构造器来处理这个异常。
所以解决方案为:
public class Demo01 {
Sheep01 s1 = new Sheep01(new Date(), "hah");
Sheep01 s2 = (Sheep01) s1.clone();
public Demo01() throws Exception{
// TODO Auto-generated constructor stub
}
}
//或者
public class Demo01 {
Sheep01 s1 = new Sheep01(new Date(), "hah");
Sheep01 s2;
public Demo01(){
try {
s2 = (Sheep01) s1.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
但是实际上,我并不是想做这样的事情,我只是想克隆一个s2,然后看克隆出来的s2和s1是否有相同的date和name,所以归根到底我就是忘了在main函数中写Demo01开始的两句代码,如此弱智的错误。
public class Demo01 {
public static void main(String[] args) throws CloneNotSupportedException {
Sheep01 s1 = new Sheep01(new Date(), "hah");
Sheep01 s2 = (Sheep01) s1.clone();
System.out.println(s1.getName()+"====="+s2.getName());
}
}
在main函数中clone函数也会报错,但是Eclipse会提示你throws或者try-catch来解决;但是如果没有在main函数中,编译器只会告诉你”Default constructor cannot handle exception type CloneNotSupportedException thrown by implicit super constructor. Must define an explicit constructor”,让你无从下手。