zoukankan      html  css  js  c++  java
  • 子类与父类的方法关系 (虚方法)

    1.子类方法与父类方法的关系分为三种
    (1)方法不同名字

    (2)同名,但参数类型和数目不同(重载)

    (3)方法名称和参数列表完全相同(方法的隐藏)

    2.继承关系下的方法重载 

    构成重载的方法具有以下特点

    (1)方法名相同。

    (2)方法的参数列表不同

    判断第2点的标准有三点,满足任一点均可认为方法参数列表不同:

    (1)参数数目不同:

    (2)参数相同类型不同;

    public int Add(int x,inty){……}

    public double Add(double x,double y){……}

    (3)参数数目和类型都相同,但参数类型出现的先后顺序不一样;

    public void f(int i ,string s){……}

    public void f(string s,int 1){……}

    需要注意的是,方法返回值类型不是方法重载的判断条件。

    如以下两个方法不能构成重载关系,VS将发生警告:

    public long Add(int x,int y){……}

    public int Add(int x,int y){……}

    3.子类隐藏父类的方法

    当子类和父类拥有完全一样的方法时,称作子类“隐藏”了父类的同名方法。需要在子类方法内加入关键字new。

     

    1 using System;
    2  using System.Collections.Generic;
    3  using System.Linq;
    4  using System.Text;
    5
    6  namespace ConsoleApplication3
    7 {
    8 class Program
    9 {
    10 static void Main(string[] args)
    11 {
    12 Child c1 = new Child();
    13 c1.Hide();
    14 Parent p1 = new Parent();
    15 p1.Hide();
    16 Parent p2 = new Child();//面向对象允许子类对象被当作父类对象使用
    17   p2.Hide();
    18 ((Child)p2).Hide();//强制类型转换
    19   Console.ReadKey();
    20 }
    21 }
    22 class Parent
    23 {
    24 public void Hide()
    25 {
    26 Console.WriteLine("我是父类!");
    27 }
    28 }
    29 class Child:Parent
    30 {
    31 public new void Hide()
    32 {
    33 Console.WriteLine("我是子类!");
    34 }
    35 }
    36 }
    虚方法好处:
    好处在多态。
    调用同一个函数方法能产生不同的效果;
    请看:
    class A
        {
            public virtual void PrintFields() { 
            Console .WriteLine ("我是A的方法");}
        }
        class B:A  
        {
            public override void PrintFields()
            {
                Console.WriteLine("我是B的方法");
            }
        }
        class C:A 
        {
        }
    
            class Test
            {
                static void Main(string[] args)
                {
                    A a;
                    a = new B();
                    a.PrintFields();//我是B的方法
                    a = new C();
                    a.PrintFields();//我是A的方法
    
                }
            }
  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/yuanws/p/2216211.html
Copyright © 2011-2022 走看看