zoukankan      html  css  js  c++  java
  • C# 面向对象的new关键字的使用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplicationTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student s = new Student("'zhangsan",19,1);
                //父类中的person say hello 没有输出,原因是隐藏了父类的方法 
    
                //如果想有意隐藏父类的同名方法 使用关键字new
                s.SayHello(); //student say hello
    
    
                Console.ReadKey();
    
    
            }
        }
    
        public class Person 
        {
            public string Name { get; set; }
    
            public int Age { get; set; }
    
            //父类构造函数
            public Person(string name,int age)
            {
                this.Name = name;
                this.Age = age;
            }
    
            public void SayHello()
            {
                Console.WriteLine("person say hello");
            }
        
        }
    
        public class Student:Person
        
        {
            public int Id { get; set; }
    
    
            //子类构造函数
            //关键字base的使用:调用父类的构造函数
            public Student(string name,int age,int id):base(name,age)
            {
                this.Id = id;
            }
    
    
            public new void SayHello()
            {
    
                Console.WriteLine("student say hello");
            }
    
        }
    }

    PS:new关键字

    1)创建对象

    2)隐藏从父类那里继承过来的同名成员

    隐藏的后果就是子类调用不到父类的成员。

  • 相关阅读:
    第十二周工作总结
    第八周工作总结
    冲刺2
    冲刺1
    用户场景分析
    用户场景分析
    水王在哪
    课堂练习-4个数的和
    《大道至简》第一章读后感
    ELF Format 笔记(三)—— Section Types
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/4057945.html
Copyright © 2011-2022 走看看