views:

103

answers:

3

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
}
A: 

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();
    }
}
this. __curious_geek
you need to make display virtual. also, why does he need the override at all?
Isaac Cambron
i dont want to override display. Is it there any other method. This is my first OO program that i m trying to implement. I only know that i cannot make display function to be static as per the requirements of my project. Suggest me the best possible way. I can make the class A non abstract or something but can make member functions static.
Shantanu Gupta
+2  A: 

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();
 }
}
Isaac Cambron
dont consider syntax, as it may be little errorinous over here, but that i will make it correct. Let me know about the solution only related to OO as i m new to OO
Shantanu Gupta
@icambron do does it mean that Display will always have single copy ?
Shantanu Gupta
Your OO is right to begin with. There's no reason you have to make Display() static. So the issue has to be something more more subtle, and you'll have to give us more information. I don't know what you mean by single copy in the context of Display. Can you be more precise?
Isaac Cambron
+1  A: 

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"

Rob van Groenewoud