Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an abstract method without specifying parameters

Tags:

c#

I am writing an abstract class with an abstract method (thus, all classes inheriting from it must implement that method). However, I do not want to specify the parameters which the method must use, as each method may take in different or no parameters. Only the name and return value should be the same.

Is there a way to do this in C#?

Thanks for any help!

like image 509
TheBoss Avatar asked Feb 01 '11 14:02

TheBoss


People also ask

Is it possible to define abstract method without declaring the abstract class?

Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.

Can an abstract method have parameters?

Yes, we can provide parameters to abstract method but it is must to provide same type of parameters to the implemented methods we wrote in the derived classes.

Can we define a abstract method?

Abstract methods are those types of methods that don't require implementation for its declaration. These methods don't have a body which means no implementation. A few properties of an abstract method are: An abstract method in Java is declared through the keyword “abstract”.

How do we define non-abstract methods in an abstract class?

Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods. For an abstract class, we are not able to create an object directly.


2 Answers

No, and it would be pointless to do so. If you didn't declare the parameters, you wouldn't be able to call the method given only a reference to the base class. That's the point of abstract methods: to allow callers not to care about the concrete implementation, but to give them an API to use.

If the caller needs to know the exact method signature then you've tied that caller to a concrete implementation, making the abstraction essentially useless.

Perhaps if you could give more details, we could suggest a more appropriate approach? For example, you might be able to make the type generic:

public class Foo<T>
{
    public abstract void Bar(T t);
}

Concrete subtypes could either also be generic, or derive from Foo<string> for example.

like image 72
Jon Skeet Avatar answered Sep 27 '22 23:09

Jon Skeet


No. Why do you need it? maybe the Command Design Pattern can help here.

like image 42
Itay Karo Avatar answered Sep 27 '22 22:09

Itay Karo