Abstract class and methods
Abstract is used to manage complexity. You cannot create instance of abstract class or interface. It is used for inheritance.
Using abstract keyword you can create abstract class.
Syntax:
abstract class mySample { //Code to Execute }
If you want to create instance of abstract class then you can do with the name of derived class.
private class myClass: myAbstract { //Code to Execute } myAbstract cls1 = new myClass();
Abstract method is method which has no implementation code into the abstract class. Implementation code is in derived class with the help of override and public access modifier.
Abstract method can only be implementation with delegates, enum, interface and structure.
Also virtual and abstract method cannot be private.
Syntax:
abstract class mySample { public abstract void Print(); }
How to define abstract class and abstract method?
Using abstract keyword you can crate abstract class and methods.
public abstract void Print();
You cannot crate instance of abstract class.
You cannot write implementation code into abstract method of abstract class.
Abstract method should be public only.
Example:
using System; class Program { static void Main() { myClass cls = new myClass(); cls.id = 1; cls.name = "Sample"; cls.Print(); } } abstract class myAbstract { public int id; public string name; public abstract void Print(); } class myClass: myAbstract { public override void Print() { Console.WriteLine("ID: {0}",id); Console.WriteLine("Name: {0}", name); } }
Output:
ID: 1
Name: Sample
In above example we have seen that abstract class is created using abstract keyword which is myAbstract. And derived class myClass which is inherits all fields and properties of abstract class.
Now, in myAbastract class you can see we have created abstract method without implementation code.
And other hands in derived class of myClass we have implement that abstract method print using override.
Now using instance of myClass in void Main program we can access abstract fields and method and get output.
How to create instance of abstract class with the help of derived class?
using System; class Program { static void Main() { myAbstract cls1 = new myClass(); cls1.id = 1; cls1.name = "Sample"; cls1.Print(); } } public abstract class myAbstract { public int id; public string name; public abstract void Print(); } class myClass : myAbstract { public override void Print() { Console.WriteLine("ID: {0}", id); Console.WriteLine("Name: {0}", name); } }
Output:
Id: 1
Name: Sample
you can also visit: www.mybook-lang.com
No comments:
Post a Comment