我正在学习Java,不理解为什么这段代码会产生以下错误:“ ArrayListClass是抽象的;无法实例化。将不胜感激。
import java.util.*;
public class ArrayListClass {
protected Object[] list;
protected int maxSize;
protected int length;
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new Object[maxSize];
}
public ArrayListClass(int size) {
maxSize = size;
list = new Object[maxSize];
length = 0;
}
public boolean isEmpty() {
return length == 0;
}
public boolean isFull() {
if (length == maxSize)
return true;
else
return false;
}
public int listSize() {
return length;
}
public int maxListSize(){
return maxSize;
}
public void print() {
System.out.print("The list contains:");
for(int i = 0; i < length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public boolean isItemAtEqual(int location, Object item) {
return (list[location].equals(item));
}
public void insertEnd(Object item) {
if(!isFull())
list[length++] = item;
}
public static void main(String [] args) {
ArrayListClass dac = new ArrayListClass(5);
dac.insertEnd(4);
dac.insertEnd(5);
dac.insertEnd(6);
dac.print();
System.out.println("dac.isItemAtEqual(0,9)"+dac.isItemAtEqual(0,9));
System.out.println("dac.isItemAtEqual(1,9)"+dac.isItemAtEqual(1,9));
}
}
最佳答案
您不能以任何编程语言实例化任何抽象类。抽象的基本构造是,它仅仅是蓝图,而不是真实的对象。它提供类的模板,并将类的形式或轮廓提供给实现类的具体类(“扩展”类...)
因此,您无法实例化ArrayListClass,因为这给出了一个蓝图。如果您扩展此类,例如DerievedArrayListClass扩展ArrayListClass,则可以实例化DerievedArrayListClass。
package com;
abstract class ArrayListClass{
protected Object [] list;
protected int maxSize;
protected int length;
public ArrayListClass(){
maxSize = 100;
length = 0;
list = new Object [maxSize];
}
public ArrayListClass(int size){
maxSize=size;
list=new Object [maxSize];
length=0;
}
public boolean isEmpty(){
return length==0;
}
public boolean isFull(){
if(length==maxSize)
return true;
else
return false;
}
public int listSize(){
return length;
}
public int maxListSize(){
return maxSize;
}
abstract void print();
public boolean isItemAtEqual(int location, Object item)
{
return (list[location].equals(item));
}
public void insertEnd(Object item){
if(!isFull())
list[length++] = item;
}
}
public class ArrayListClassImpl extends ArrayListClass{
public ArrayListClassImpl(int i) {
super(i);
}
public void print(){
System.out.print("The list contains:");
for(int i = 0; i < length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public static void main(String [] args){
ArrayListClass dac = new ArrayListClassImpl(5);
dac.insertEnd(4);
dac.insertEnd(5);
dac.insertEnd(6);
dac.print();
System.out.println("dac.isItemAtEqual(0,9)"+dac.isItemAtEqual(0,9));
System.out.println("dac.isItemAtEqual(1,9)"+dac.isItemAtEqual(1,9));
}
}