OOPS
WHAT IS DIFFERENCE BETWEEN ABSTRACT CLASS , INTERFACE AND VIRTUAL FUNCTION.
VIRTUAL FUNCTION:
By declaring base class function as virtual, we allow the function to be overridden in any of derived class.
Example of Virtual Method in .Net:
Class parent
{
virtual void hello()
{
{
virtual void hello()
{
Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.
ABSTRACT CLASS:
1. ABSTRACT CLASS CONTAINS ABSTRACT METHOD AND NON ABSTRACT METHOD
2. ABSTRACT MEANS ONLY DECLARATION OF METHOD WITHOUT BODY .
eg (public abstract void abstractmethod();)
3
3. ABSTRACT METHOD SHOULD BE OVERRIDDEN IN DRIVED CLASS WHERE AS NON ABSTRACT MEMBER IS OPTIONAL.
EG:
4. ABSTRACT METHOD USE OVERRIDE KEY WORD IN CHILD CLASS.
5 5. ABSTRACT CLASS CANNOT BE INSTANTIATED.
INTERFACE:
. INTERFACE IS NOT A CLASS. IT IS AN ENTITY TO DEFINE INTERFACE KEYWORD.
. INTERFACE ONLY CONTAINS ABSTRACT METHOD. AND ALL INTERFACE METHOD SHOULD BE USE IN DRIVED CLASS
1 eg: class sample1
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
}
}
interface sample
{
int z;
}
output: error Interfaces cannot contain fields
2 eg:class sample2
{ public static void Main() { System.Console.WriteLine("Hello Interfaces"); } } interface abc { void test() { System.Console.WriteLine("test interface"); } }
output: Interface members cannot have a definition
3.
. INTERFACES ARE IMPLEMENTED, INTERFACE CONTAINS ABSTRACT METHODS BUT WE DON’T HAVE TO DEFINE ABSTRACT KEY WORD.
ΓΌ EG :Interface Sample
{
public void Method1();
void method2();
}
{
public void Method1();
void method2();
}
MAIN DIFFERENCE
NOTE: A CLASS CAN IMPLEMENT MULTIPLE INTERFACE BUT A CLASS CANNOT INHERIT MULTIPLE CLASSES (IN .NET WE CAN ACHIEVE MULTIPLE INHERITANCE USING INTERFACE).
ENCAPSULATION: ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.
BY DEFAULT ACCESS SPECIFIERS IS INTERNAL FOR ALL.
· Public: Access to all code in the program
· Private: Access to only members of the same class
· Protected: Access to members of same class and its derived classes
· Internal: Access to current assembly
· Protected Internal: Access to current assembly and types derived from containing class
No comments:
Post a Comment