Shantanu Gupta
Shantanu Gupta

Reputation: 21108

How to access functions from abstract class without making them static?

I want to create a class that can only be inherited, for that i know it should be made abstract. But now the problem is that i want to use functions of that class without making them static. How can i do that.

public abstract Class A
{
 A()
 {}
 public void display()
 {}
}

public Class B:A
{
 base.A() // this is accessible
 this.display() // this is not accessible if i dont make this function static above
}

Upvotes: 1

Views: 11622

Answers (3)

Rob van Groenewoud
Rob van Groenewoud

Reputation: 1884

Your example will not compile, you could consider something like this:

using System;

public abstract class A
{
    protected A()
    {
        Console.WriteLine("Constructor A() called");
    }
    public void Display()
    {
        Console.WriteLine("A.Display() called");
    }
}

public class B:A
{
    public void UseDisplay()
    {
        Display();
    }
}

public class Program
{
    static void Main()
    {
        B b = new B();
        b.UseDisplay();
        Console.ReadLine();
    }
}

Output:

Constructor A() called
A.Display() called

Note: Creating a new B() implicitly calls A(); I had to make the constructor of A protected to prevent this error: "'A.A()' is inaccessible due to its protection level"

Upvotes: 2

this. __curious_geek
this. __curious_geek

Reputation: 43217

Here's how you can do this..

public abstract class A
{
    public virtual void display() { }
}

public class B : A
{
    public override void display()
    {
        base.display();
    }

    public void someothermethod()
    {
        this.display();
    }
}

Upvotes: 0

user24359
user24359

Reputation:

That's not true. You don't have to make Display() static; you can call it freely from the subclass. On the other hand, you can't call the constructor like that.

Maybe it's just an error in the example, but the real issue with the code you have is that you can't put method calls in the middle of your class definition.

Try this:

public abstract class A
{
 public void Display(){}
}

public class B:A
{
 public void SomethingThatCallsDisplay()
 {
  Display();
 }
}

Upvotes: 2

Related Questions