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

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!