Question #42347

Explain the terms Encapsulation and Abstraction

Expert's answer

Here is the processed document with the code blocks restored and formatted:

---

Answer on Question#42347- Programming, C#

1. Explain the terms Encapsulation and Abstraction

Solution.

Abstraction

Abstraction allows us to represent complex real world in simplest manner. It is process of identifying the relevant qualities and behaviors an object should possess, in other word represent the necessary feature without representing the background details. Abstraction is a process of hiding work style of an object and showing only those information which are required to understand the object. Abstraction means putting all the variables and methods in a class which are necessary.

Encapsulation

It is a process of hiding all the internal details of an object from the outside real world. The word Encapsulation, like Enclosing into the capsule. It restrict client from seeing its internal view where behavior of the abstraction is implemented. In Encapsulation, generally to hide data making it private and expose public property to access those data from outer world. Encapsulation is a method for protecting data from unwanted access or alteration. Encapsulation is the mechanism by which Abstraction is implemented.

Difference between Abstraction and Encapsulation

Abstraction is a process. It is the act of identifying the relevant qualities and behaviors an object should possess. Encapsulation is the mechanism by which the abstraction is implemented.


Examples

Abstraction

The **abstract** modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the **abstract** modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

In this example, the class **Square** must provide an implementation of **Area** because it derives from **ShapesClass**:


abstract class ShapesClass
{
abstract public int Area();
}
class Square : ShapesClass
{
int side = 0;
public Square(int n)
{
side = n;
}
// Area method is required to avoid
// a compile-time error.
public override int Area()
{
return side * side;
}
static void Main()
{
Square sq = new Square(12);
Console.WriteLine("Area of the square = {0}", sq.Area());
}
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
}
// Output: Area of the square = 144


Abstract classes have the following features:

- An abstract class cannot be instantiated.

- An abstract class may contain abstract methods and accessors.

- It is not possible to modify an abstract class with the modifier because the two modifiers have opposite meanings. The **sealed** modifier prevents a class from being inherited and the **abstract** modifier requires a class to be inherited.

- A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Use the **abstract** modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:

- An abstract method is implicitly a virtual method.

- Abstract method declarations are only permitted in abstract classes.

- Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example:

- `public abstract void MyMethod();`

The implementation is provided by an overriding method `override (C# Reference)`, which is a member of a non-abstract class.

- It is an error to use the `static` or `virtual` modifiers in an abstract method declaration.

Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

- It is an error to use the **abstract** modifier on a static property.

- An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

An abstract class must provide implementation for all interface members.

An abstract class that implements an interface might map the interface methods onto abstract methods. For example:


interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}


In this example, the class `DerivedClass` is derived from an abstract class `BaseClass`. The abstract class contains an abstract method, `AbstractMethod`, and two abstract properties, `X` and `Y`.


abstract class BaseClass  // Abstract class
{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod();  // Abstract method
public abstract int X  { get; }
public abstract int Y  { get; }
}
class DerivedClass : BaseClass
{
public override void AbstractMethod()
{
_x++;
_y++;
}
public override int X  // overriding property
{
get
{
return _x + 10;
}
}
public override int Y  // overriding property
{
get
{
return _y + 10;
}
}
static void Main()
{
DerivedClass o = new DerivedClass();
o.AbstractMethod();
Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
}
}
// Output: x = 111, y = 161


In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:

BaseClass bc = new BaseClass(); // Error

you will get an error saying that the compiler cannot create an instance of the abstract class 'BaseClass'.

Encapsulation

The **Encapsulate Field** refactoring operation enables you to quickly create a property from an existing field, and then seamlessly update your code with references to the new property.

When a field is public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, you can disallow direct access to fields.

To create the new property, the **Encapsulate Field** operation changes the access modifier for the field that you want to encapsulate to private, and then generates get and set accessors for that field. In some cases, only a get accessor is generated, such as when the field is declared read-only.

The refactoring engine updates your code with references to the new property in the areas specified in the **Update References** section of the **Encapsulate Field** dialog box.

To create a property from a field

1. Create a console application named **EncapsulateFieldExample**, and then replace Program with the following example code.


class Square
{
// Select the word 'width' and then use Encapsulate Field.
public int width, height;
}
class MainClass
{
public static void Main()
{
Square mySquare = new Square();
mySquare.width = 110;
mySquare.height = 150;
// Output values for width and height.
Console.WriteLine("width = {0}", mySquare.width);
Console.WriteLine("height = {0}", mySquare.height);
}
}


2. In the Code Editor, place the cursor in the declaration, on the name of the field that you want to encapsulate. In the example below, place the cursor on the word width:


public int width, height;


3. On the Refactor menu, click Encapsulate Field.

The Encapsulate Field dialog box appears.

You can also type the keyboard shortcut CTRL+R, E to display the Encapsulate Field dialog box. You can also right-click the cursor, point to Refactor, and then click Encapsulate Field to display the Encapsulate Field dialog box.

4. Specify settings.

5. Press ENTER, or click the OK button.

6. If you selected the Preview reference changes option, then the Preview Reference Changes window opens. Click the Apply button.

The following get and set accessor code is displayed in your source file:


public int Width
{
get { return width; }
set { width = value; }
}


The code in the Main method is also updated to the new Width property name.


Square mySquare = new Square();
mySquare.Width = 110;
mySquare.height = 150;
// Output values for width and height.
Console.WriteLine("width = {0}", mySquare.Width);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS