using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InheritDemo
{
class Program
{
static void Main(string[] args)
{
Inherit();
}
private static void Inherit()
{
Person person = new Person("name1", "address1");//父类属性
Employee employee1 = new Employee("name2", "address2");//子类继承父类属性
Employee employee2 = new Employee("name3", "address3", "unit3");//子类继承父类属性并添加自己特有的属性
person.Print1();//父类方法
person.Print2();//父类方法
employee1.Print1();//子类继承父类方法
employee2.Print2();//子类重写父类方法
Console.ReadLine();
}
}
public class Employee : Person//子类继承父类
{
public Employee() { }
public Employee(string name,string address):base(name,address) //子类继承父类属性
{
this.Name = name;
this.Address = address;
}
public Employee(string name, string address, string unit):base(name, address) //子类继承父类属性并添加自己特有的属性
{
this.Name = name;
this.Address = address;
this.Unit = unit;
}
private string unit;//单位
public string Unit
{
get { return unit; }
set { unit = value; }
}
public override void Print1()//继承父类方法
{
base.Print1();
}
public override void Print2()//重写父类方法
{
Console.WriteLine("{0},{1},{2}", Name, Address,Unit);
}
}
public class Person//基类
{
public Person() { }
public Person(string name, string address)
{
this.Name = name;
this.Address = address;
}
private string name;//姓名
public string Name
{
get { return name; }
set { name = value; }
}
private string address;//地址
public string Address
{
get { return address; }
set { address = value; }
}
public virtual void Print1()//虚拟方法可以被重写
{
Console.WriteLine("{0},{1}", Name, Address);
}
public virtual void Print2()//虚拟方法可以被重写
{
Console.WriteLine("{0},{1}", Name, Address);
}
}
}
c# 单重继承
最新推荐文章于 2021-12-14 07:30:00 发布