类继承和接口继承

类的继承

设计一个学生类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。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值