Hello
Can anyone give me an C# code example which covers all 4 oops principal.
I want all in only one example.
-Thanks
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Mar 14, 2011, 11:17 AM EDT
using System;
class Parent // encapsulation - encapsulates data and method into a class
{
private string name; // data hiding - hides state from outside code
public string Name // property exposes state to outside code
{
get { return name; }
set { name = value; }
}
public Parent(string name)
{
this.name = name;
}
public Parent(){}
public void MyMethod()
{
Console.WriteLine("Hello from Parent.MyMethod");
}
public virtual void MyVirtMethod()
{
Console.WriteLine("Hello from Parent.MyVirtMethod");
}
}
class Derived : Parent // inheritance - inherits from Derived
{
public override void MyVirtMethod()
{
Console.WriteLine("Hello from Derived.MyVirtMethod");
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
d.MyMethod(); // inheritance - MyMethod inherited from Parent
Parent p = d;
p.MyVirtMethod(); // polymorphism - Derived.MyVirtMethod called because p refers to a Derived object
p = new Parent("Fred");
Console.WriteLine(p.Name);
Console.ReadKey();
}
}
Rahul Shah19 reputationPosted Mar 14, 2011, 9:08 PM EDT
VulpesRank #55 · 29.2K reputationPosted Mar 15, 2011, 6:46 AM EDT
Encapsulation provides a mechanism for hiding data or functionality in the form of 'access modifiers' and therefore has a close relationship with abstraction.
It's difficult to represent abstraction in the example as it's something which is considered more when designing your classes rather than implementing them. However, if you imagine some operation which the class needs to carry out internally and then expose the result (but not how it is achieved) to the user, then that's a form of abstraction.
Rahul Shah19 reputationPosted Mar 15, 2011, 8:52 AM EDT
VulpesRank #55 · 29.2K reputationPosted Mar 15, 2011, 8:59 AM EDT
A better example would be a method which returns a random number. Here, even an expert user would not how the random number was arrived at because there are various algorithms which can generate pseudo-random numbers.
All that matters to the user is that the number is sufficiently random for his/her purposes - the algorithm used is unimportant.
Rahul Shah19 reputationPosted Mar 15, 2011, 9:07 AM EDT
Bdw,Now I finally got all 4 oops principal clearly.
Thanks a lot for your help.