我正在尝试让我的程序说:

小鸡goes

猪去了

Elsie mo

美女去mo



但我不断收到2个错误,即:

错误:类NamedCow中的构造函数NamedCow无法应用于给定类型;

有什么办法可以修复它,以便我的程序可以输出以下内容:

小鸡goes

猪去了

Elsie mo

美女去mo

import static java.lang.System.*;
import java.util.*;

public class Java5203{
    public static void main(String[] args) {
        new Environment();
}}


class Environment
{
    Farm mcDonald;

    public Environment()
    {
        mcDonald = new Farm();

        run();
    }

    public void run()
    {
        out.println();
        mcDonald.animalSounds();
        out.println();
    }
}

class Farm
{
    ArrayList<Animal> liveStock = new ArrayList<Animal>();

    public Farm()
    {
        liveStock.add( new Chick()           );
        liveStock.add( new Pig()             );
        liveStock.add( new NamedCow("Elsie") );
        liveStock.add( new NamedCow("Bell")  );
    }

    public void animalSounds()
    {
        for(int i=0;i<liveStock.size();i++)
        {
            out.println(liveStock.get(i).getType() + " goes " + liveStock.get(i).getSound());
        }
    }
}
abstract class Animal
{
    protected String myType;

    protected String mySound;

    public abstract String getSound();

    public abstract String getType();
}


class Cow extends Animal
{
    Cow()
    {
        myType = "cow";
        mySound = "moo";
    }

    public String getSound()
    {
         return mySound;
    }

    public String getType()
    {
         return myType;
    }
}

class Chick extends Animal
{
    Chick()
    {
        myType = "chick";
        mySound = "chirp chirp";
    }

    public String getSound()
    {
         return mySound;
    }

    public String getType()
    {
         return myType;
    }
}

class Pig extends Animal
{
    Pig()
    {
        myType = "pig";
        mySound = "oink";
    }

    public String getSound()
    {
         return mySound;
    }

    public String getType()
    {
         return myType;
    }
}


class NamedCow extends Cow
{
    public String getSound()
    {
         return mySound;
    }

    public String getType()
    {
         return myType;
    }
}

最佳答案

您正在调用NamedCow构造函数,并传入String参数,

liveStock.add( new NamedCow("Elsie") );


但是此类没有采用String参数的构造函数,实际上NamedCow类根本没有构造函数。

解决方案:给它一个构造函数,该构造函数接受String并使用它来设置字段。例如。,

public class Foo {
   private String bar;

   public Foo(String bar) {
      this.bar = bar;
   }

   // getters, setters, other methods,...
}

关于java - Java多态性“无法应用于给定类型”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28975671/

10-13 00:09