zoukankan      html  css  js  c++  java
  • c#基础知识第十二节

    继承和多态

    继承(继承具有传递性)

    //(父类)
    class Animal
    {
    public string Name
    {
    get;
    set;
    }
    public void shout()
    {
    Console.WriteLine("动物叫");
    }
    }
    //(子类)
    class Dog : Animal
    {
    public void printName()
    {
    Console.WriteLine("名字 :"+Name);
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    //实例化子类
    Dog d = new Dog();
    d.Name = "沙皮狗";
    d.printName();
    d.shout();
    Console.ReadKey();
    }
    }

    如果拥有父类的话,在调用自身构造方法之前会先调用父类的构造方法。

    隐藏基类(父类)方法

    class Animal //父类
    {
    //父类方法
    public void Shout()
    {
    Console.WriteLine("动物叫!");
    }
    }
    //子类
    class Dog:Animal
    {
    //子类方法
    public new void Shout() //使用new关键字来隐藏基类方法
    {
    Console.WriteLine("狗叫!");
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Dog d = new Dog();
    d.Shout();
    Console.ReadKey();
    }
    }

    密封(sealed)不能被继承

    object类

    class program

    {
    static void Main(string[] args)
    {
    Console.WriteLine(42.ToString());
    int i = 42;
    Console.WriteLine(i.ToString());

    Console.ReadKey();

    }
    }

    多态:同一方法在不同类中(希望父类方法在子类中得到一定的改进)

    class Animal //父类
    {
    //父类方法
    public virtual  void Shout()//使用virtual关键字来修饰要重写的父类方法
    {
    Console.WriteLine("动物叫!");
    }
    }
    //子类
    class Dog:Animal
    {
    //子类方法
    public override  void Shout() //使用override关键字来修饰,重写父类方法
    {
    Console.WriteLine("狗叫!");
    }
    }

    里氏转换原则

    1.Animal an=new Dog();

    2.Aniaml an=new Dog();

      Dog dog=(Dog)an;//将父类变量an强制转换为子类类型dog

    base关键字

    专门用于在子类中访问父类的成员

  • 相关阅读:
    浅析Java中的final关键字
    Eclipse导入到web项目没有run on server
    解决web项目无法部署到eclipse配置的本地tomcat
    Eclipse 导入外部项目无法识别为web项目并且无法在部署到tomcat下
    JAVA – 虚函数、抽象函数、抽象类、接口
    jsp分页
    连接数据库查询数据
    (转)解决emacs中切换输入法冲突
    sqoop的使用
    hive的使用03
  • 原文地址:https://www.cnblogs.com/zhang1997/p/7682474.html
Copyright © 2011-2022 走看看