因此,我创建了三个类; PetStore,宠物和鸟。 PetStore类是主类,pet扩展了PetStore,然后Bird扩展了Pet
现在,我使用以下代码创建了驱动程序类。
public class Main{
public static void main(String[] args){
//create a pet objects
Bird macaw = new Bird("hyacinth macaw", 300.99, 48.0);
//create a pet store
PetStore happyPetsInc = new PetStore();
//add the pets to the pet store
happyPetsInc.addPet(macaw);
我正在尝试将Bird对象添加到PetStore中的arraylist中。
我收到错误消息:“不兼容的类型:鸟不能转换为java.lang.String”
有人标记了此内容,并说要发布PetStore和Bird类,因此这里是:
public class PetStore
{
//varibles
String pet;
//ArrayList
ArrayList<String> Pets = new ArrayList<String>();
//constructor
public PetStore(){
}
/**
* add the paramameter to the ArrayList
* @param pet
* @return void
*/
public void addPet(String pet){
Pets.add(pet);
}
/**
* removes the paramater to the ArrayList
* @param pet
* @return true(success) false(failure)
*/
public boolean sellPet(String pet){
this.pet = pet;
if (Pets.contains(pet)){
Pets.remove(pet);
return true;
}else{
return false;
}
}
/**
* counts the number of elements in the ArrayList
* @param none
* @return int, the number of the elements in Pets
*/
public int getInventoryCount(){
return Pets.size();
}
/**
* displays information about the pets in the ArrayList
* @param none
* @return void
*/
public String toString(){
for (int i = 0; i < Pets.size(); i++){
System.out.println("Pet #" + (i + 1));
String index = Pets.get(i);
return index.toString();
}
return "\n";
}
}
public class Bird extends Pet
{
//varibale
double wingspan;
//constuctor
public Bird(String species, double cost, double wingspan){
super(species, cost);
this.wingspan = wingspan;
}
/**
* Sets the wingspan of the bird
* @param wingspan
* @return none
*/
public void setWingspan(double wingspan){
this.wingspan = wingspan;
}
/**
* Gets the wingspan of the bird
* @param none
* @return double
*/
public double getWingspan(){
return this.wingspan;
}
/**
* Displays strings describing the bird
* @param none
* @return String
*/
public String toString(){
return "Species: " + species + "\nCost: $" + cost + "\nBird (Wingspan: " + wingspan + " inches)";
}
}
最佳答案
面向对象编程的思想是使类和类(对象)的实例代表现实生活中的对象。因此,PetStore是关于宠物而不是字符串的。这样做:
在PetStore中替换
ArrayList<String> Pets ...
addPet(String pet)...
sellPet(String pet)...
与
ArrayList<Pet> Pets
addPet(Pet pet)
sellPet(Pet pet)
另外,在PetStore.toString()中替换
String index = Pets.get(i);
用
Pet index = Pets.get(i);
关于java - 不兼容的类型:无法转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60825223/