类的继承
设计一个学生类Student和它的一个子类Undergraduate,就是简单的类继承,创建一个包含两个参数的构造方法和一个包含三个参数的构造方法,用于给属性赋值,并在测试类中进行调用。
namespace chouxiang
{
class Student
{
public String name;
public int age;
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public Student(string name, int age, string degree) : this(name, age)
{
}
public void show()
{
Console.WriteLine("姓名:" + name + "年龄:" + age);
}
}
class Undergraduate : Student
{
public String degree;
public Undergraduate(String name, int age, String degree) : base(name, age, degree)
{
this.name = name;
this.age = age;
this.degree = degree;
}
public void Show()
{
Console.WriteLine("姓名:" + name + "年龄:" + age + " 学位:" + degree);
}
}
public class Program
{
public static void Main(String[] args)
{
Student student = new Student("张三 ", 22);
student.show();
Undergraduate undergraduate = new Undergraduate("WJJ ", 22, "理学学士");
undergraduate.Show();
}
}
}
运行结果
接口的继承
设计一个Shape接口和它的两个实现类Square和Circle,在shape接口中定义一个抽象方法,其参数设为double,返回double类型的值,Square和Circle分别继承了Shape中定义的抽象对象,并在测试类中返回Square和Circle的值。
namespace chouxiang
{
interface shape
{
double area(double x);
}
class square : shape
{
public double area(double x)
{
return x * x;
}
}
class circle : shape
{
public double area(double x)
{
return Math.PI * x * x;
}
}
internal class Class2
{
static void Main(string[] args)
{
square square = new square();
circle circle = new circle();
Console.WriteLine("正方形的面积为:{0}",square.area(2));
Console.WriteLine("圆形的面积为:{0}", circle.area(3));
}
}
}
运行结果
**Tips:**以上就是类继承和接口继承的实例结果,代码片段很简单,但前提是要有思路才简单,886。