Class both extends an abstract class and implements an interface - c#

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.

You need to
implement the interface in AbstractExample
or get a reference to Example
Example example = new Example();

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.

If you only know the abstract class, it suggests that you know the actual type via an instance of Type. Therefore, you could use generics:
private T SomeMethod<T>()
where T : new(), AbstractExample, ExampleInterface
{
T instance = new T();
instance.SomeMethodOnAbstractClass();
instance.SomeMethodOnInterface();
return instance;
}

Use:
Example example = new Example();
Updated after more information:
If you are sure it implements ExampleInterface, you can use
AbstractClass example = new Example();
ExampleInterface exampleInterface = (ExampleInterface)example;
exampleInterface.InterfaceMethod();
You can also make sure it really implements it by checking the interface with
if (example is ExampleInterface) {
// Cast to ExampleInterface like above and call its methods.
}
I don't believe Generics help you as those are resolved compile time and if you only have a reference to the AbstractClass the compiler will complain.
Edit: So more or less what Owen said. :)

I think this example will help you:
public interface ICrud
{
void Add();
void Update();
void Delete();
void Select();
}
public abstract class CrudBase
{
public void Add()
{
Console.WriteLine("Performing add operation...");
Console.ReadLine();
}
public void Update()
{
Console.WriteLine("Performing update operation...");
Console.ReadLine();
}
public void Delete()
{
Console.WriteLine("Performing delete operation...");
Console.ReadLine();
}
public void Select()
{
Console.WriteLine("Performing select operation...");
Console.ReadLine();
}
}
public class ProcessData : CrudBase, ICrud
{
}
var process = new ProcessData();
process.Add();

Related

Creating an object with the interface name vs class name in C# [duplicate]

I have seen an Interface instance being generated from a class many times. Why do we use interface this way? An interface instance is created only itself with the help of the derived class and we can access only these interface members through this instance. How does this give an advantage? I'm so confused.
interface IPrint
{
void Print();
}
class Sample : IPrint
{
public void Print()
{
Console.WriteLine("Print...");
}
public void Sample()
{
Console.WriteLine("Sample...");
}
}
class Program
{
static void Main(string[] args)
{
IPrint print = new Sample();
print.Print();
}
}
Interfaces define that a class MUST be able to do something. This means that you know the object being worked on will do what you want to be able to do. It allows you greater freedom and is one of the advantages of OOP. This is a deep topic but a very basic example would be this:
public interface IAnimal
{
string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "Woof, woof";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "Meow";
}
}
public class Parrot : IAnimal
{
public string Speak()
{
return "Sqwark!";
}
}
Then you could use any animal you like!
class Program
{
static void Main(string[] args)
{
// Writes Woof, Woof
IAnimal animal = new Dog();
Console.WriteLine(animal.Speak());
// Now writes Meow
animal = new Cat();
Console.WriteLine(animal.Speak());
// Now writes Sqwark etc
animal = new Parrot();
Console.WriteLine(animal.Speak());
}
}
This also allows you to then get into things like Inversion Of Control where you would take an item in like this and you could pass a dog, cat or parrot and the method would always work, not knowing or caring which animal it was:
public void ShoutLoud(IAnimal animal)
{
MessageBox.Show("Shout " + animal.Speak());
}
This then makes ShoutLoud unit testable because you could use a mock object rather than a real animal. It basically makes your code flexible and dynamic rather than rigid and tightly coupled.
Also, expanding on Matthew's question. In C# you can only inherit from one base class but you can have multiple interfaces. So, you could have:
public class Dog : IAnimal, IMammal, ICarnivor
This allows you to have small interfaces (recommended) that then allow you to build up so giving maximum control over what an item can / must do.
Using an interface this way gives you the ability to create methods that use standard template of the interface. So here you might have many classes of printer that all inherit from IPrinter
class SamsungPrinter : IPrinter
{
// Stuff and interface members.
}
class SonyPrinter : IPrinter
{
// Stuff and interface members.
}
interface IPrinter
{
void Print();
}
So for each type SamsungPrinter, SonyPrinter, etc. you can pre-process using something like
public static void PreProcessAndPrint(IPrinter printer)
{
// Do pre-processing or something.
printer.Print();
}
You know from inheriting from IPrinter and using that type in the method parameters that you can always safely use the Print method on what ever object is passed.
Of course there are many other uses for using interfaces. One example of their use is in design patterns, in particular the Factory and Strategy patterns. The description of which and examples can be found here.
I hope this helps.
But how does this differ from, for example, using a base class with virtual methods?
You are all in the assumption that one programmer or one program writes the interface and the classes, but this doesn't always have to be this way.
Maybe you have a complete finished program that works with animals and you have this worked out using:
public abstract class Animal { public abstract string Speak(); }
And then some day you download some awesome DLL from nuget that shows pictures for animals. The class library contains a contract - interface - 'IAnimal':
namespace AwesomeAnimalLibrary
{
public interface IAnimal
{
string AnimalName;
}
}
The class library also maybe contains :
namespace AwesomeAnimalLibrary
{
public class AnimalPhotos
{
[Byte] GetPhotos(IAnimal animal);
}
}
What could you do now ? Your bas class Animal can implement the AwesomeAnimalLibrary IAnimal interface and that's it.
Don't assume that other people will use you abstract base classes but work together using interface contracts.
Interface can not have instance because interface implements only signatures of properties or methods. Interface is just a pointer to an instance of some class:
interface IExample
{
// method signature
void MyMethod();
}
public class MyClass : IExample
{
// method implementation
public void MyMethod()
{
ConsoleWriteline("This is my method");
}
}
// interface pointing to instance of class
IExample ie = new MyClass();
ie.MyMethod();

Java Inheritance Constraints

I am trying to port some code I wrote in C# to Java, but do not know all of the Java syntax yet. I also have no idea what this type of thing is called, so it is harder to search..I am calling it "inheritance constraints."
Basically, is there a java equivalent to this C# code:
public abstract class MyObj<T> where T : MyObj<T>, new()
{
}
Thanks.
Edit:
Is there any way to do this:
public abstract class MyObj<T extends MyObj<T>> {
public abstract String GetName();
public virtual void Test() {
T t = new T(); // Somehow instantiate T to call GetName()?
String name = t.GetName();
}
}
Not quite. There's this:
public abstract class MyObj<T extends MyObj<T>>
but there's no equivalent to the new() constraint.
EDIT: To create an instance of T, you'll need the appropriate Class<T> - otherwise type erasure will byte you.
Typically you'd add this as a constructor parameter:
public MyObj(Class<T> clazz) {
// This can throw all kinds of things, which you need to catch here or
// propagate.
T t = clazz.newInstance();
}
Judging by your comment above, you're looking for the following construct:
An interface with which you will interact with MyObj objects in code... you will be calling the test() method (standard style in Java is camelcase methods, capitalized classes/interfaces)
public interface IMyObj {
public void test();
}
You will want the abstract superclass... for the example that you've chosen, you don't NEED to specify any genericism, although you absolutely can if the actual implementation is more reliant on type safety... this class should implement the IMyObj interface:
public abstract class MyObj implements IMyObj {
String name;
public abstract String getName();
public void test() {
name = getName();
}
}
From here you would write your subclasses to MyObj...
public class MySubObj1 extends MyObj {
public String getName() { return "MySubObj1"; }
}
public class MySubObj2 extends MyObj {
public String getName() { return "MySubObj2"; }
}
Then you safely and correctly use the following snippet in another class:
IMyObj obj = new MySubObj1();
obj.test();
The key is that you use interfaces to hide the implementation, and use abstract classes to hold common code that subclasses will utilize in their implementations.
Hope this helps!

Sealing an interface after implementing it

I am working on a small project and I came across that problem.
The project output is a library containing an interface. I would like to implement that interface and seal the functions in it like this if possible:
public interface ITest
{
void SomeMethod();
}
class A : ITest
{
public sealed override SomeMethod()
{
}
}
The idea is to have the interface available to everyone and have some specialized class that implements it. The exception is that I want to make sure that if someone create a specialized class of type A, he/she won't be able to change the method's behavior.
The problem is you can't put the "override" keyword in there since the method isn't declared as "virtual" in the interface. And you can't declare it as "virtual" in the interface since it's not allowed. And you can't remove the "override" keyword since it's needed by "sealed".
Any workaround or brainstorming idea would be welcome, but if someone can come up with a solution that includes an interface, I'd be really happy to learn it!
Thanks!
EDIT: Forget this question! Like Ani said, I forgot that by default method in C# are sealed. Seems like it's always good to go back to the basics once in a while...
I may have completely misunderstood the question, but if your intention is to seal the method in A, you can just do:
class A : ITest
{
public void SomeMethod() { ... }
}
Unlike Java, methods in C# are sealed by default. Subclasses of A won't be able to override the method since it hasn't been marked virtual.
On the other hand, if your intention is to mark the method 'almost sealed' in the interface, so that it forces upon an implementing class to immediately seal it, that isn't possible. It isn't (and shouldn't be) the business of the interface to dictate such details of implementation - an interface is meant to represent a specification.
Use an abstract base class with internal visibility. This base class is not visible outside of the library but allows you to seal the method and the class still implements the interface.
public interface ITest
{
void SomeMethod();
}
internal abstract class SuperA : ITest
{
public abstract void SomeMethod();
}
class A : SuperA
{
public sealed override void SomeMethod()
{
}
}
Your understanding of sealed keyword is incorrect. As a method modifier, sealed is used to prevent a virtual method(defined in the base class) to be override in the next generation of derived classes. For example:
class Base
{
public virtual void M() { }
}
class Derived : Base
{
public sealed override void M() { }
}
class A : Derived
{
public override void M() { } //compile error, M is sealed in Derived
}
Developers can always use new modifier to define a method with the same name in the derived class, that hides the one defined in the base class.
if someone create a specialized class
of type A, he/she won't be able to
change the method's behavior.
If "specialized class" means a class derived from A, the answer is: he can always hide the method in A, but he can't change the method's behavior.
Why not use an abstract class like below.
Haven't tested it but this should work?
public abstract class Test
{
public virtual void SomeMethod() {}
//OR
public abstract void SomeMethod();//MSDN says:
//an abstract method is implicitly virtual
}
class A : Test
{
public sealed override SomeMethod()
{
}
}
Methods in C# are sealed by default.. Here is a sample
class Program
{
static void Main(string[] args)
{
A obj = new A();
obj.SomeMethod();
b ss = new b();
ss.SomeMethod();
Console.ReadLine();
}
}
public interface ITest { void SomeMethod(); }
class A : ITest { public void SomeMethod() {
Console.WriteLine("SomeMethod Called from Class A object");
} }
class b : A
{
//public override void SomeMethod()
//{
// Console.WriteLine("Called from Class B Object");
//}
}

static method cannot implement interface method, why?

interface IXXX
{
void Foo();
}
class XXX : IXXX
{
public static void Foo()
{
Console.WriteLine("From XXX");
}
}
class Program
{
static void Main(string[] args)
{
XXX.Foo();
}
}
Compiler error: XXX.Foo() cannot implement an interface member because it is static.
Why can't a static method implement an interface method?
See this thread from JoelOnSoftware describing the reasons behind this.
Basically the interface is the contract between the consumer and the provider, and a static method belongs to the class, and not each instance of the class as such.
An earlier question on SO also deal with the exact same question:
Why Doesn't C# Allow Static Methods to Implement an Interface?
An interface defines the behaviour that an object must respond to.
As Foo is a static method, the object doesn't respond to it. In other words, you couldn't write...
XXX myXXX = new XXX();
myXXX.Foo();
In other words, myXXX doesn't fully satisfy the requirements of the interface.
IF we look at interfaces as a promise that an object can perform the methods listed in the interface, then ths idea of static implementation becomes problematic. If the implemetion is static, then you can't write new ImplementingObject().ImplementedMthod. The object can't perform the method, the class can.
You use interface to avoid using concrete class during instantiation. You can't access static method through instantiated class, so implementing interface methods with static methods is not allowed.
Well, I believe it should allowed in case of generic type parameter. It probably simplified contractual singleton class. Here is an example:
public interface IEntity {
// some constrains...
DataRow ObjToRow(object obj);
object RowToObj(DataRow dr);
}
//T would be any class inherites from IEntity with default contructor signature.
public interface IMyContract {
T read<T>() where T : IEntity;
void write<T>(T object) where T : IEntity;
}
//everything in the class is static
public static class SqlProvider : IMyContract {
public static T read<T>() where T: IEntity {
DataRow dr = [reading from database]
return T.RowToObj(dr);
}
//compile error here....
public static void write<T>(T obj) where T : IEntity {
DataRow dr = T.ObjToRow(obj);
[ ... commit data row dr to database ... ]
}
}
public static class MyAppleEntity : IEntity {
[... implement IEntity contract normally ... ]
}
public static class MyOrangeEntity : IEntity {
[... implement IEntity contract normally ... ]
}
public class MyTest {
void reading() {
MyAppleEntity apple = SqlProvider.Read<MyAppleEntity>();
MyOrangeEntity orange = SqlProvider.Read<MyOrangeEntity>();
SqlProvider.write<MyAppleEntity>(apple);
SqlProvider.write<MyOrangeEntity>(orange);
}
}
The only time a type reference implicitly is in the SqlProvider.read() and write() and T is well identity at point of invoke. Without static implementation of interface I'm forced to write like this.
public class MyAppleEntity : IEntity {
[... implement IEntity contract normally ... ]
}
.....
public T read<T>() where T: IEntity, new() {
DataRow dr = [reading from database]
return new T().RowToObj(dr);
}
Very little different but not quite as elegant.
Because interface member are public and overridable, and that static method cannot by design be overrided or abstract, Interfaces are here to define an accessible contract that must be implemented by their concrete implementation (with as many steps of abstract implementations & inherited interfaces between) and as far as I know there is no way to create an abstract static method.

Using interfaces on abstract classes in C#

I'm learning C# coming from C++ and have run into a wall.
I have an abstract class AbstractWidget, an interface IDoesCoolThings, and a class which derives from AbstractWidget called RealWidget:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget : IDoesCoolThings
{
void IDoesCoolThings.DoCool()
{
Console.Write("I did something cool.");
}
}
public class RealWidget : AbstractWidget
{
}
When I instantiate a RealWidget object and call DoCool() on it, the compiler gives me an error saying
'RealWidget' does not contain a
definition for 'DoCool'
I can cast RealWidget object to an IDoesCoolThings and then the call will work, but that seems unnecessary and I also lose polymorphism (AbstractWidget.DoCool() will always be called even if i define RealWidget.DoCool()).
I imagine the solution is simple, but I've tried a variety of things and for the life of me can't figure this one out.
You're running into the issue because you used explicit interface implementation (EII). When a member is explicitly implemented, it can't be accessed through a class instance -- only through an instance of the interface. In your example, that's why you can't call DoCool() unless you cast your instance to IDoesCoolThings.
The solution is to make DoCool() public and remove the explicit interface implementation:
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool() // DoCool() is part of the abstract class implementation.
{
Console.Write("I did something cool.");
}
}
// ...
var rw = new RealWidget();
rw.DoCool(); // Works!
In general, you use EII in two cases:
You have a class that must implement two interfaces, each of which contains a member that has an identical name/signature to another member in the other interface.
You want to force clients not to depend on the implementation details of your class, but rather on the interface that's being implemented by your class. (This is considered a good practice by some.)
The way you implement the interface is explicit implement void IDoesCoolThings.DoCool(), if you choose implicit implement interface.
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool()
{
Console.Write("I did something cool.");
}
}
Then it will work.
Read this :
C# Interfaces. Implicit implementation versus Explicit implementation
Change your declaration to:
public abstract class AbstractWidget : IDoesCoolThings
{
public void DoCool()
{
Console.Write("I did something cool.");
}
}
You should do it this way:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget
{
public void DoCool()
{
Console.WriteLine("I did something cool.");
}
}
public class Widget : AbstractWidget, IDoesCoolThings
{
}
Usage:
var widget = new Widget();
widget.DoCool();

Categories

Resources