//出生年龄必须大于0
//public int Age { get; set; }
//这种封装可以修改属性的限制 propfull+TAB
private int age;//private:私有 成员变量
public int Age //public:公共 属性
{
get { return age; }
set {
if (value> 0)
{
age = value;
}
else
{
Console.WriteLine("年龄必须大于等于0");
}
}
}
继承中的重写
例子:
public virtual void Eat()//虚方法
{
Console.WriteLine("吃白萝卜");
}
public override void Eat()//重写方法
{
Console.WriteLine("吃肉");
}
/* 应用程序,该程序包括3个类:Monkey类、People类和主类E。要求:
(1) Monkey类中有个构造方法:Monkey (String s),并且有个public void speak()方法,在speak方法 中输出“咿咿呀呀……”的信息。
(2)People类是Monkey类的子类,在People类中定义方法speak(),在speak方法中输出“不错嘛!会说话了!”的信息。
(3)在People类中新增方法void think(),在think方法中输出“别说话!认真思考!”的信息。
(4)在主类E的main方法中创建Monkey与People类的对象类测试这2个类的功能。
*/
class Program
{
static void Main(string[] args)
{
Mokey mo = new Mokey("Tom");
mo.Speak();
People po = new People("Helaa");
po.Speak();
po.Think();
}
}
class Mokey
{
public Mokey(String s)
{
this.name = s;
}
public string name;
public void Speak()
{
Console.WriteLine("我是猴子" + name);
Console.WriteLine("咿咿呀呀....");
}
}
class Test3:Mokey
{
public Test3(string s):base(s)
{
}
public new void Speak()
{
Console.WriteLine("我是人类"+name);
Console.WriteLine("不错嘛!会说话了!");
}
public void Think()
{
Console.WriteLine("别说话!认真思考!");
}
}
}
/*
1)定义一个类,描述一个矩形,包含有长、宽两种属性,和计算面积方法。
(2)编写一个类,继承自矩形类,长方体,具有长、宽、高属性,和计算体积的方法。
(3)编写一个测试类,对以上两个类进行测试,创建一个长方体,定义其长、宽、高,输出其底面积和体积。
*/
class Program
{
static void Main(string[] args)
{
Square s = new Square();
Cub s1 = new Cub();
s1.a = 10.0;
s1.b = 12.0;
s1.c = 5.0;
s1.area();
s1.Vol();
}
}
class Square
{
public double a;
public double b;
public virtual void area()
{
Console.WriteLine("矩形的面积:"+(a*b));
}
}
class Cub:Square
{
public double c;
public override void area()
{
Console.WriteLine("长方体的底面积:{0:0.0}",(a*b));
}
public void Vol()
{
Console.WriteLine("长方体的体积:{0:0.0}",(a*b*c));
}
}
/*
设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。
小车类Car是Vehicle的子类,其中包含的属性有载人数loader。
卡车类Truck是Car类的子类,其中包含的属性有载重量payload。
每个类都有构造方法和输出相关数据的方法。
最后,写一个测试类来测试这些类的功能。
*/
class Program
{
static void Main(string[] args)
{
Car c1 = new Car(4,600,4);
c1.Print();
c1.Hold();
Truck c2 = new Truck(6, 1000, 3, 800);
c2.Print();
c2.Hold();
c2.Load();
}
}
class Vehicle
{
int wheels;
double weight;
public Vehicle(int wheels,double weight)
{
this.weight = weight;
this.wheels = wheels;
}
public virtual void Print()
{
Console.WriteLine("车轮的个数是:"+wheels+" "+"车重:{0:0.0}",weight);
}
}
class Car:Vehicle
{
public int loader;
public Car(int wheels, double weight,int loader) : base(wheels,weight)
{
this.loader = loader;
}
public override void Print()
{
base.Print();
}
public virtual void Hold()
{
Console.WriteLine("这辆车能载"+loader+"人");
}
}
class Truck : Car
{
double payload;
public Truck(int wheels, double weight, int loader, double payload) : base(wheels, weight,loader)
{
this.payload = payload;
}
public override void Print()
{
base.Print();
}
public override void Hold()
{
base.Hold();
}
public void Load()
{
Console.WriteLine("这辆车的载重是{0:0.0}",payload);
}
}