是否有可能没有变量且带有方法的类? [英] Is it possible to have class without variables and with methods?
本文介绍了是否有可能没有变量且带有方法的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用多态性解决这个问题.我需要用5种动物打印出这首歌的诗句.每只动物都重复这首诗,并为该动物使用适当的声音,例如,母牛发出呜呜"声,鸭子发出嘎嘎声"等.我想问一下是吗可能只具有方法的类.另外这是我的代码.
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();
}
}
推荐答案
是
一个类不必具有方法或字段/变量
A class doesnt have to have methods or fields / variables
这篇关于是否有可能没有变量且带有方法的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文