Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - Is it possible to have class without variables and with methods?

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes

A class doesnt have to have methods or fields / variables


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...