C#中继承的代码实现方法。
编写一个名叫CellPhone的类,该类继承自Phone类(其中Phone类包含两个属性color和price),请为CellPhone类定义一个名叫maxBatterLife的实例变量并提供以下两个构造函数:
1、两个输入参数的构造函数(参数1为color,参数2为price)
2、三个输入参数的构造函数(参数1为color,参数2为price,参数3为maxBatterLife) 创建一控制台应用程序,程序设计要求如下:
当用户的输入的参数为两个时,打印以下语句: “This phone’s color is ***,price is ***”当用户的输入的参数为三个时,打印以下语句: “This CellPhone’s color is ***,price is ***, maxBatterLife is ***”
1、前述要求中的红色星号表示的是取类的属性所得到的值,要求将值打印到控制台上。
2、在处理多个输入参数时,可以用空格或逗号还分隔参数,读取用户控制台输入字符串的命令为Console.ReadLine();
代码
Phone
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Phone
{
}
}
CellPhone
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class CellPhone : Phone
{
public CellPhone(string color, double price)
{
this._color = color;
this._price = price;
}
public CellPhone(string color, double price, string maxBatterLife)
: this(color, price)
{
this.maxBatterLife = maxBatterLife;
}
private string _color;
private double _price;
public string maxBatterLife;
public string Color
{
get { return this._color; }
set { this._color = value; }
}
public double Price
{
get { return this._price; }
set { this._price = value; }
}
}
}
Test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Test
{
public static void Main()
{
while (true)
{
Console.WriteLine("------------------------");
Console.Write("请输入手机颜色:");
string color = Console.ReadLine();
Console.Write("请输入手机价格:");
double price = double.Parse(Console.ReadLine());
Console.Write("请输入手机最长使用周期(可选,敲回车跳过):");
string maxBatterLife = Console.ReadLine();
CellPhone phone;
if (maxBatterLife == "")
{
phone = new CellPhone(color, price);
Console.WriteLine("This phone’s color is {0},price is {1} ", phone.Color, phone.Price);
}
else
{
phone = new CellPhone(color, price, maxBatterLife);
Console.WriteLine("This phone’s color is {0},price is {1},maxBatterLife is {2} ", phone.Color, phone.Price, phone.maxBatterLife);
}
}
}
}
}
效果