Object Oriented Programming (CS-127) LAB #
08
LAB # 08
Abstraction: Working with Abstract Classes, Interfaces and Sealed
Classes
Abstraction
Abstraction is a principle of object-oriented programming language (OOP), and it is used to hide
the implementation details and display only essential features of the object. Data abstraction can
also be defined as the process of hiding certain details and showing only essential information to
the user. Abstraction can be achieved with either abstract classes or interfaces.
Abstract Modifier
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.
Abstract Classes and Methods
Abstract class: is a restricted class that cannot be used to create objects (in order to access it, it
must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the derived class (inherited from).
Important points to note
An abstract class is incomplete and hence it cannot be instantiated.
An Abstract class can only be used as base class.
An Abstract class cannot be a sealed class.
A non-abstract class derived form an abstract class must provide the implementation of all
the inherited abstract methods.
An abstract class can have both abstract and regular methods:
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
[Link]("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Object Oriented Programming (CS-127) LAB #
08
Animal myObj = new Animal(); // Will generate an error (it cannot create an instance of the
abstract class or interface 'Animal')
To access the abstract class, it must be inherited from another class. Remember from the
Inheritance class that we use the : symbol to inherit from a class, and that we use the override
keyword to override the base class method.
Example:
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
[Link]("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
[Link](); // Call the abstract method
[Link](); // Call the regular method
}
}
Sealed Modifier
To prevent a class from being inherited, precede its declaration with sealed keyword. As you
might expect, it is illegal to declare a class as both abstract and sealed because an abstract class is
incomplete by itself and relies upon its derived classes to provide complete implementations.
Object Oriented Programming (CS-127) LAB #
08
Here is an example of a sealed class:
sealed class A
{
..............
}
The following class is illegal.
class B : A
{
// ERROR! Can't derive from class A// ...
}
As the comments imply, it is illegal for class B to inherit class A because class A is declared as
sealed. One other point: sealed can also be used on virtual methods to prevent form further
overrides.
For example, assume a base class called B and a derived class called D. A method declared
virtual in B can be declared sealed by D. This would prevent any class that inherits D from
overriding the method. This situation is illustrated by the following:
class B {
public virtual void MyMethod()
{
/* ... */
}
}
class D : B {
// This seals MyMethod() and prevents further overrides.
sealed public override void MyMethod()
{
/* ... */
}
}
class X : D {
// Error! MyMethod() is sealed!
public override void MyMethod()
{
/* ... */
}
}
Because MyMethod( )is sealed by D, it can’t be overridden by X.
Object Oriented Programming (CS-127) LAB # 08
Interfaces
An interface is a reference type that represents a set of function members, but does not implement them i-e
it cannot have method body and cannot be instantiated. Its implementation must be provided by class or
struct. The class or struct which implements the interface, must provide the implementation of all the
methods declared inside the interface.
Interfaces are declared by using the interface keyword. Here is a simplified form of an interface
declaration:
Interface name
{
ret-type method-name1(param-list);
ret-type method-name2(param-list);
// ...
ret-type method-nameN(param-list);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, the name of the interface is specified after the class name in just the same way that a base class
is specified. The general form of a class that implements an interface is shown here:
Class class-name: interface-name
{
// class-body
}
The name of the interface being implemented is specified in interface-name. When a class implements an
interface, the class must implement the entire interface. It cannot pick and choose which parts to
implement, for example. A class can implement more than one interface. When a class implements more
than one interface, specify each interface in a comma-separated list. A class can inherit a base class and
also implement one or more interfaces. In this case, the name of the base class must come first in the
comma-separated list.
Let's see the example of interface in C# which has draw() method. Its implementation is provided by two
classes: Rectangle and Circle.
Example 1:
using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
Object Oriented Programming (CS-127) LAB # 08
public void draw()
{
[Link]("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
[Link]("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
[Link]();
d = new Circle();
[Link]();
}
}
Output:
Note: Interface methods are public and abstract by default. You cannot explicitly use public and abstract
keywords for an interface method.
using System;
public interface Drawable
{
public abstract void draw(); //Compile Time Error
}
Example 2:
using System;
namespace interfaces
{
interface ISeries
{
int getNext();
void SetStart(int val );
Object Oriented Programming (CS-127) LAB # 08
void reset();
}
class ByTwos : ISeries
{
int start, val=0;
public int getNext()
{
return val+=2;
}
public void SetStart(int v)
{
start = v;
val = start;
}
public void reset()
{
val= start;
}
}
class InterfaceDemo
{
static void Main(string[] args)
{
ByTwos obj1 = new ByTwos();
for (int i = 0; i < 5; i++)
{
[Link]("Next Value is " + [Link]());
}
[Link]("Resetting:");
[Link]();
for (int i = 0; i < 5; i++)
{
[Link]("Next Value is " + [Link]());
}
[Link]("Starting From 100");
[Link](100);
for (int i = 0; i < 5; i++)
{
[Link]("Next Value is " + [Link]());
}
Object Oriented Programming (CS-127) LAB # 08
[Link]();
}
}
}
Output:
Next value is 2
Next value is 4
Next value is 6
Next value is 8
Next value is 10
Resetting
Next value is 2
Next value is 4
Next value is 6
Next value is 8
Next value is 10
Starting frm 100
Next value is 102
Next value is 104
Next value is 106
Next value is 108
Next value is 110
Multiple Inheritance Using Interface
With interfaces, we can achieve multiple inheritance in C#.
Example-1
using System;
namespace interfaces
{
interface IGetSum
{
void getSum();
}
interface ICalSum
{
int calSum(int a, int b);
}
Object Oriented Programming (CS-127) LAB # 08
class Addition : IGetSum, ICalSum
{
int sum;
public int calSum(int a, int b)
{
sum = a + b;
return sum;
}
public void getSum()
{
[Link]("Sum is :"+sum);
}
}
class InterfaceDemo
{
static void Main(string[] args)
{
Addition a = new Addition();
[Link](5, 7);
[Link]();
[Link]();
}
}
}
Example-2
using System;
namespace interfaces
{
interface IA
{
void display();
}
interface IB
{
void display();
}
class test : IA, IB
{
void [Link]()
{
[Link]("Display of IA");
}
Object Oriented Programming (CS-127) LAB # 08
void [Link]()
{
[Link]("Display of IB");
}
}
class InterfaceDemo
{
static void Main(string[] args)
{
test t = new test();
((IA)t).display();
((IB)t).display();
[Link]();
}
}
}
Object Oriented Programming (CS-127) LAB # 08
LAB TASKS
Task 1:
Write a program to demonstrate the multiple inheritance.
Task 2:
Write a program to demonstrate abstract and sealed modifiers.
Task 3:
Create an interface Itransaction that contains methods:
void showTransaction()
double getAmount()
Now create a class named Transaction that inherits Itransaction and contains members:
private string tCode
private string date
private double amount
Add default constructor and parametrized constructor to initialize the values and implement
showTransaction() and getAmount() methods in class.
Task 4:
Design the program that will create Invoice and Employee classes both represent things for which the
company must be able to calculate a payment amount. Both classes implement the Payable interface.
Interface Payable contains public abstract method getPaymentAmount. So a program can invoke method
getPaymentAmount on Invoice objects, Employee objects and salariedEmpolyee object alike. This
enables the polymorphic processing of Invoices and Employees required for the company’s accounts
payable application.
Create class Invoice to represent a simple invoice that contains billing information for only one kind of
part. The class declares private instance variables partNumber, partDescription, quantity and pricePerItem
that indicate the part number, a description of the part, the quantity of the part ordered and the price per
item. Class Invoice also contains a constructor, get and set methods that manipulate the class’s instance
variables and a display method that returns a String representation of an Invoice object. Methods
setQuantity and setPricePerItem ensure that the quantity and pricePerItem obtain only nonnegative values.