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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Mar 14, 2011, 3:17 PM
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 ShahPosted Mar 15, 2011, 1:07 PM
Bdw,Now I finally got all 4 oops principal clearly.
Thanks a lot for your help.
VulpesPosted Mar 15, 2011, 12:59 PM
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 ShahPosted Mar 15, 2011, 12:52 PM
VulpesPosted Mar 15, 2011, 10:46 AM
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 ShahPosted Mar 15, 2011, 1:08 AM