继承2
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承 { public class chinese : person//定义一个chinese派生类,继承自person类 { public string shengxiao;//生肖 public override void sayhello(string shengxiao, string name, int age, string sex) { base.sayhello();//调用基类的无参方法 this.name = name; this.age = age; this.sex = sex; this.shengxiao = shengxiao; Console.WriteLine("你好!我的生肖是{0},我的名字叫{1},我今年{2}岁,我的性别是{3}。", shengxiao, name, age, sex); } public void hello()//无参构造函数 { shengxiao = "牛"; name = "小红"; age = 10; sex = "女"; Console.WriteLine("你好!我的生肖是{0},我的名字叫{1},我今年{2}岁,我的性别是{3}。", shengxiao, name, age, sex); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承作业 { public class english : person//定义一个english派生类,继承自person类 { public string xingzuo;//星座 public override void sayhello(string xingzuo, string name, int age, string sex) { base.sayhello();//调用基类的无参方法 this.xingzuo = xingzuo; this.name = name; this.age = age; this.sex = sex; Console.WriteLine("hello!my star sign is {0},my name is {1},i'm {2} years old ,my sex is {3}.", xingzuo, name, age, sex); } public void hello()//无参构造函数 { xingzuo = "巨蟹座"; name = "小红"; age = 10; sex = "女"; Console.WriteLine("hello!my star sign is {0},my name is {1},i'm {2} years old ,my sex is {3}.", xingzuo, name, age, sex); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承作业 { //基类 public class person { public string name;//姓名 public int age;//年龄 public string sex;//性别 //虚方法--子类可以重写 public virtual void sayhello(string x, string name, int age, string sex)//有参构造方法 { this.name = name; this.age = age; this.sex = sex; Console.WriteLine("hello!我的名字叫{0},我今年{1}岁,我的性别是{2}", name, age, sex); } //无参构造方法 public void sayhello() { name = "小红"; age = 10; sex = "女"; Console.WriteLine("hello!我的名字叫{0},我今年{1}岁,我的性别是{2}", name, age, sex); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承作业 { class Program { static void Main(string[] args) { //在主方法实例化 person a = new person(); english b = new english(); chinese c = new chinese(); Console.WriteLine("\t三个类的无参构造:"); a.sayhello(); b.hello(); c.hello(); Console.WriteLine("\t三个类的有参构造和子类调用父类的无参构造:"); a.sayhello("","小明",12,"男"); b.sayhello("cancer","xiaomin", 12, "male"); c.sayhello("牛","小明", 12, "男"); //停止看结果 Console.ReadLine(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构