父类computer代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace leiku
{
public class computer
{
public computer() { }//类中本身自带的无参构造函数
public computer(string brand,string model,double price,string color)//也可以定义有参的构造函数
{
this.Brand = brand;
this.Model = model;
this.Price = price;
this.Color = color;
}
public string Brand { get; set; }
public string Model { get; set; }
public double Price { get; set; }
public string Color { get; set; }
public string ShowInfo()
{
return string.Format("品牌{0},系列:{1}价格:{2}颜色:{3}", Brand, Model, Price, Color);
}
}
}
子类Desktop.cs的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace leiku
{
public class Desktop:computer
{
public string CaseColor { get; set; }
}
}
控制台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using leiku;
namespace 继承
{
class Program
{
static void Main(string[] args)
{
computer com = new computer();//实例化computer类
//理解:声明父类的变量,无非就是想使用父类中的所有属性,方法,字段等,那么子类的实例中包含所有父类中的属性,方法和字段(不严谨),所以可以将一个子类的实例赋给父类的变量。
computer com1 = new Desktop();//父类和子类一起定义一个对象,父类必须在前,子类必须在后
//用一个父类变量指向一个子类实例是可以的,用一个子类变量指向一个父类实例是不行的
//computer com1=aaa;---这只是定义一个变量
}
}
}