Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class both extends an abstract class and implements an interface

What if I have a class that both extends an abstract class and implements an interface, for example:

class Example : AbstractExample, ExampleInterface
{
    // class content here
}

How can I initialize this class so I can access methods from both the interface and the abstract class?

When I do:

AbstractExample example = new Example();

I cannot access methods from the interface.

like image 885
Richard Knop Avatar asked Apr 25 '09 18:04

Richard Knop


2 Answers

You need to

  • implement the interface in AbstractExample
  • or get a reference to Example

Example example = new Example();

like image 89
Stefan Steinegger Avatar answered Oct 06 '22 00:10

Stefan Steinegger


The last example will tie you to a solid instance of either the interface or abstract class which I presume is not your goal.The bad news is you're NOT in a dynamically typed language here, so your stuck with either having a reference to a solid "Example" objects as previously sprcified or casting/uncasting i.e:

AbstractExample example = new Example();
((IExampleInterface)example).DoSomeMethodDefinedInInterface();

Your other alternitives are to have both AbstractExample and IExampleInterface implement a common interface so you would have i.e.

abstract class AbstractExample : ICommonInterface
interface IExampleInterface : ICommonInterface
class Example : AbstractExample, IExampleInterface

Now you could work with ICommonInterface and have the functionality of both the abstract class and the implementation of your IExample interface.

If none of these answers are acceptable, you may want to look at some of the DLR languages that run under the .NET framework i.e. IronPython.

like image 40
Owen Avatar answered Oct 06 '22 00:10

Owen