what is the meaning of data hiding

后端 未结 7 1830
小鲜肉
小鲜肉 2021-01-19 03:23

One of the most important aspects of OOP is data hiding. Can somebody explain using a simple piece of code what data hiding is exactly and why we need it?

7条回答
  •  孤城傲影
    2021-01-19 04:12

    Data Hiding is defined as hiding a base class method in a derived class by naming the new class method the same name as the base class method.

    class Person
    {
      public string AnswerGreeting()
      {
         return "Hi, I'm doing well. And you?";
      }
    }
    
    class Employee : Person
    {
       new public string AnswerGreeting()
       {
          "Hi, and welcome to our resort.";
       }
    }
    

    In this c# code, the new keyword prevents the compiler from giving a warning that the base class implementation of AnswerGreeting is being hidden by the implementation of a method with the same name in the derived class. Also known as "data hiding by inheritance".

提交回复
热议问题