有没有人能告诉我如何在这段代码上运行main方法呢? 我想检查是否有任何编译时错误或运行时错误,但我收到此错误消息“无法找到或加载主类应用程序”。
class Book {
private static int internalID = 0;
private String isbn;
private int myID;
public Book(String isbnP) {
if (isbnP == null) {
throw new IllegalArgumentException("null ISBN not accepted");
}
isbn = isbnP;
myID = internalID++;
}
public String getBookinfo() {
return isbn;
}
public String toString() {
return "<" + myID + "," + isbn + ">";
}
// To Do: Override Object.equals()
// Two objects are equal iff isbn of the two books are same
}
class ComSBook extends Book {
private String category;
public ComSBook(String isbnP, String catP) {
super(isbnP);
category = catP;
}
@override
public String getBookInfo() {
return "ComS " + category + " " + super.getBookinfo();
}
}
class NetworkBook extends ComSBook {
private boolean isWithCD;
public NetworkBook (String isbnP, boolean withCD){
super(isbnP,"Network");
isWithCD = withCD;
}
@override
public String getBookInfo(){
return super.getBookInfo() + " withCD: " + isWithCD;
}
}
class ReviewPolymorp{
public static void main(String[] args){
Book abook = new Book("A-1");
Book bbook = new Book("B-1");
ComSBook csbook = new ComSBook("C-11", "General");
NetworkBook netbook = new NetworkBook("N-11", true);
System.out.println(abook);
System.out.println(bbook);
System.out.println(csbook);
System.out.println(netbook);
abook = csbook;
System.out.println(abook.getBookinfo());
bbook = netbook;
System.out.println(bbook.getBookinfo());
netbook = (NetworkBook) bbook;
System.out.println(netbook.getBookinfo());
netbook = (NetworkBook) csbook;
System.out.println(netbook.getBookinfo());
netbook = csbook;
}
}
答案 0 :(得分:2)
您的文件应该是ReviewPolymorp.java
而class ReviewPolymorp{
应该是public
,因为它是使用main
方法的程序的起始点
您可能还想检查项目中的Main类是否为ReviewPolymorp
。我只知道如何在Netbeans中做到这一点
ReviewPolymorp
i主要类别具有完全限定名称,例如mypackage.ReviewPolymorp
答案 1 :(得分:0)
当我将代码复制到我的IDE(它是eclipse)时,编译错误出现在这一行:
netbook = csbook;
您不能将超类的实例强制转换为子类。
禁用此行后,我会在运行代码后从控制台输出:
<0,A-1>
<1,B-1>
Exception in thread "main" <2,C-11>
<3,N-11>
C-11
N-11
N-11
java.lang.ClassCastException: com.test.ComSBook cannot be cast to com.test.NetworkBook
at com.test.ReviewPolymorp.main(ReviewPolymorp.java:75)
上面的编译错误也是同样的问题。
禁用这三行后
netbook = (NetworkBook) csbook;
System.out.println(netbook.getBookinfo());
csbook = netbook;
代码运行良好,无需任何修改。