java - 新的抽象等无法实例化类型
问题描述
大家好,我在编写程序时遇到了麻烦,因为它一直给我错误:无法实例化类型。我是抽象/实现的新手,所以我怀疑这是这个程序的问题。这是我到目前为止所拥有的:
import java.util.*;
import java.net.URL;
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
public class Program5 {
public abstract static class Animal implements Comparable<Animal>{
String OwnerName;
int birthYear;
public int billBalance;
String Species;
String feature;
public Animal() {}
public Animal(String OwnerName,int birthYear,int billBalance,String Species,String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public void storeFile(Animal[] x) throws Exception{
BigInteger size = new BigInteger("1");
URL url=new URL("http://yoda.com/~pawang/CPS1/Program5_veterinarian_input.txt");
Scanner input = new Scanner(url.openStream());
HttpURLConnection conn;
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
size = BigInteger.valueOf(conn.getContentLength());
while (input.hasNext()){
for(int i = 1;i<size.bitLength();i++) {
x[i] = new Animal();
String line = input.nextLine();
}
}
}
public int getBalance() {
return billBalance;
}
public static void sorts(Animal[] x) {
}
}
}
似乎问题出在第 33 行: x[i] = new Animal();
解决方案
抽象意味着类中的某些内容仅被声明,而从未定义。
例如,Person
创建一个要扩展的类,并且有一个方法doThings
:假设我们创建Worker
了一个Student
类,Worker
它doThings
应该可以工作,而不是Student
应该学习,而不Person
需要做任何事情,而是为了有继承,所以ArrayList<Person>
在每个元素上执行类似的操作这个:doThings
doThing
Person
Person
doThing
public void abstract doThing();
通过这个语句,我们告诉 JVM,只要我们有一个这种类型的对象,就有一个doThing
方法,如果我们不实现这个:这就是为什么如果类是抽象的,你就不能创建一个新对象,因为声明的东西从未被实施。
如果要实例化该类的对象,则应创建一个覆盖抽象方法的新类。
这只是一个简短的解释,还有更多的内容,你可以用它做更多的事情。
推荐阅读
- c - gcc - 警告:函数“get_int”的隐式声明
- scala - 未找到:程序集中的值 assemblyJarName assemblyJarName := s"${name.value.replace(' ','-')}-${version.value}.jar"
- laravel - lararvel uuid 作为主键
- ios - 以 std::__1::system_error 类型的未捕获异常终止:互斥锁失败:无效参数
- c++ - 用 C++ 制作多类型容器(地图)
- c - 在第 5 行查找值“pp-p”的给定示例中,为什么在解释中这些值除以 2?
- windows - 如何通过快捷键执行powershell脚本?
- java - Univocity 获取索引线同时解析
- java - 更改来自 apache camel 的 http 响应和 body 响应
- python - 如何摆脱方括号并每行打印一个输出?(Python)