Is it possible to have class without variables and

2020-01-20 08:32发布

问题:

I'm solving this problem with polymorphism. I need to print out verse of the song with 5 animals.The verse is repeated for each animal and the appropriate sound for the animal is used eg cows go “moo”, ducks go “quack” etc. I would like to ask is it possible to have a class only with methods. In addition here is my code.

public class Animal
{
    public virtual void PrintSong()
    {

    }
}

public class Cow : Animal
{
    public override void PrintSong()
    {
        Console.WriteLine("I go \"Mooo\" (I'm a cow, I'm a cow, I'm a cow)");        
    }
}

public class Pig : Animal
{
    public override void PrintSong()
    {
        Console.WriteLine("I go \"Oink\" (I'm a pig, I'm a pig, I'm a pig)");  
    }
}

static void Main(string[] args)
{
    Animal[] animals = new Animal[2];
    animals[0] = new Cow();
    animals[1] = new Pig();

    foreach (Animal a in animals)
    {
        a.PrintSong();
    }
}

回答1:

Yes

A class doesnt have to have methods or fields / variables