James Johnson
James Johnson

Reputation: 37

Proper using abstract class in c#

I tried to implant abstract class in my program like that:

public abstract class DataAccess2
{
    public abstract void FindElements();
}
public class Traingle : DataAccess2
{
    public override void FindElements()
    {
        Console.WriteLine("Loading");
    }
}
public class TraingleAngular : DataAccess2
{
    public override void FindElements()
    {
        Console.WriteLine("Angular");
    }
}
    static void Main()
    {

        List<DataAccess2> dataAccess1s = new List<DataAccess2>()
        {
             new Traingle(),
            new TraingleAngular()
        };

        foreach (var data1 in dataAccess1s)
        {
            data1.FindElements();
        }

        Console.ReadLine();
    }

And i am not sure if i use proper abstract class.Can i make more optimizations? Sorry for bad English

Upvotes: 0

Views: 262

Answers (2)

OO7
OO7

Reputation: 690

Definitely, you can create an abstraction for any class that derived from it's base class. So that could be implemented more flexible. Example:

abstract class BaseClass
{
    public abstract void test();
}

...

BaseClass sub1 = new SubTest1();
BaseClass sub2 = new SubTest2();

sub1.test();

List<BaseClass> list = new List<BaseClass>();

list.Add(sub1);
list.Add(sub2);
...

Upvotes: 0

David Mkheyan
David Mkheyan

Reputation: 528

This is an example of an abstract class usage, but you don't use any of the benefits that the abstract class has when compared to interfaces.

  1. You can create some methods that have their default implementation
  2. You can create a constructor that takes some arguments

Upvotes: 1

Related Questions