首页 > 解决方案 > 新的抽象等无法实例化类型

问题描述

大家好,我在编写程序时遇到了麻烦,因为它一直给我错误:无法实例化类型。我是抽象/实现的新手,所以我怀疑这是这个程序的问题。这是我到目前为止所拥有的:

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();

标签: javaarraysobjectinterface

解决方案


抽象意味着类中的某些内容仅被声明,而从未定义。
例如,Person创建一个要扩展的类,并且有一个方法doThings:假设我们创建Worker了一个Student类,WorkerdoThings应该可以工作,而不是Student应该学习,而不Person需要做任何事情,而是为了有继承,所以ArrayList<Person>在每个元素上执行类似的操作这个:doThingsdoThingPersonPersondoThing

public void abstract doThing();

通过这个语句,我们告诉 JVM,只要我们有一个这种类型的对象,就有一个doThing方法,如果我们不实现这个:这就是为什么如果类是抽象的,你就不能创建一个新对象,因为声明的东西从未被实施。
如果要实例化该类的对象,则应创建一个覆盖抽象方法的新类。

这只是一个简短的解释,还有更多的内容,你可以用它做更多的事情。


推荐阅读