C# 8 default interface implementation and inheritance - c#

I want to use C# 8 default interface implementation to face a performance issue in my code.
Actually, I have this intefaces :
public interface IDataAdapter {}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
}
I actually have to do reflection across all IDataAdapter, check generic type and call Insert by reflection for a specific T instance. What I wish to do is :
public interface IDataAdapter
{
void InsertValue(object value);
}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
public void InsertValue(object value) => Insert(value as T);
}
The compiler says to use the keyword new to mask the inherited method. However, the only thing I'm trying to accomplish is to have a non-generic method already implemented to make all IDataAdapter<T> implementations to only have to implement the generic version.
Is this something I can accomplish or it's still impossible ? I already know that using an abstract class is a way to solve this issue, but I want to allow a developper to have a class that implements many IDataAdapter...
This is my current reflection code :
public IEnumerable<IDataAdapter> DataAdapters { get; }
public Repository(IEnumerable<IDataAdapter> dataAdapters)
{
DataAdapters = dataAdapters;
}
public async Task SaveAsync()
{
foreach (var item in aggregates)
{
foreach (var dataAdapter in DataAdapters)
{
if (dataAdapter.GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericArguments()[0] == item.GetType()))
{
dataAdapter.GetType().GetMethod("Insert", new[] { item.GetType() }).Invoke(dataAdapter, new[] { item });
}
}
}
}

From an object oriented point of view, what you are trying to do can't be done.
Suppose you create the following class hierarchy:
public interface IFoo{}
public interface IBar{}
public class A: IFoo{}
public class B: IFoo{}
public class C:IFoo,IBar {}
And then the following adapters:
public class TestA : IDataAdapter<A>{}
public class TestB : IDataAdapter<B>{}
public class TestC : IDataAdapter<C>{}
public class TestIFoo : IDataAdapter<IFoo>{}
public class TestIBar : IDataAdapter<IBar>{}
public class TestIBoth : IDataAdapter<IFoo>,IDataAdapter<IBar>{}
What should happen if TestA receive an instance of A is quite easy. But what about TestIFoo receive a C? Currently your reflection code won't work because you test type equality (does C equals IFoo? No! Even if C as IFoo is ok).
This breaks Liskov substitution principle. If something works with a class then it should also work with any of its subclasses.
Let's suppose you fix above point. Now what about TestIBoth receiving a C? Is there two different implementation of Insert in it? Of course, this is required by inheritence! But then... do you have to insert C twice? Or do you have to insert it just once in the first fitting method?
The reason why you have to go through reflection is because all those questions needs an algorithmic answer. Your compiler won't be able to answer (which makes the language prevent it by the way)
In the end I would strongly recommend to use a very different solution (like the one proposed by Wim Coenen)

I recognize this problem where you need to look up the IDataAdapter implementation which knows how to handle a certain type of item. I've done something similar for a "view plugin" system, where I would look for the view plugin that knows how to render a certain type. This is useful if you can't know in advance what type of objects you'll need to render.
As far as I know, trying to shoehorn more compile-time type safety into this pattern won't really work, or if it does then it won't actually provide any benefits. I would just declare IDataAdapter like this:
public interface IDataAdapter
{
void InsertValue(object value);
Type SupportedType { get; }
}
If a data adapter supports multiple types, you can make it IEnumerable<Type> SupportedTypes instead, or maybe replace the property by a bool SupportsType(Type) method.

Related

c# abstract classes -- "one or the other" alternate functions

Here's one, I have an abstract class like this...
public abstract class SpaceshipManager
{
...
public abstract void BuildWith(ParseObject po);
// "Or ..."
public abstract void BuildWith(string label);
...
}
The sense is, the derived classes must implement BuildWith a ParseObject, "OR", they can implement BuildWith using a string.
Now, at the moment I just do this ...
public abstract void BuildWith(object data);
Which is fine - but is there a better way?
Another way to look at it, you could have two methods
BuildKeidranType()
BuildBastionType()
The concept is that derived classes have to implement at least one of these.
Is there any such thing in c#?
You could use generics:
public abstract class SpaceshipManager<T>
{
public abstract void BuildWith(T source);
}
public class StringBuilderSpaceshipManager : SpaceshipManager<ParseObject> { ... }
Well there is nothing like that in c#. Generics could have given you a way out.
But seeing that you are deriving from MonoBehavior, i am assuming it's Unity you are working with, where there are constraints like the class name must be same as the file name etc. etc. which don't give too many options for generic behaviors. So avoiding generic classes and focusing on generic methods.
The following is a very crude example using generics just for fun and might not be much better than your current example where you take the parameter as an object. Nevertheless here goes:
public abstract class SpaceshipManager: MonoBehaviour
{
public void BuildWith<T>(T po)
{
if (ValidateBuildParam<T>())
{
Build<T>(po);
}
}
protected abstract bool ValidateBuildParam<T>();
protected abstract void Build<T>(T type);
}
public class DerivedA : SpaceshipManager
{
protected override void Build<T>(T po)
{
//Build here
}
protected override bool ValidateBuildParam<T>()
{
return (typeof(T) != typeof(ParseObject)) ? false : true;
}
}
public class DerivedB : SpaceshipManager
{
protected override void Build<T>(T po)
{
//Build here
}
protected override bool ValidateBuildParam<T>()
{
return (typeof(T) != typeof(string)) ? false : true;
}
}
Now there are some drawbacks like the following usage wont be incorrect:
SpaceshipManager spMan = new DerivedA();
spMan.BuildWith<int>(5);
This will compile and run but would build nothing. So it would be good if you change the return type of BuildWith, return null if Validation fails or a bool true or false
No, there's no such thing.
If the derived class implemented only one of the overloads, how would the caller know which one is implemented?
NO, such things which you are asking is not available in c#. In c# there is interface but you would have to implement all of the methods in derived class because if you would implement one of those caller would get confused.
As others have already told you, you cannot define abstract methods as optional to be implemented somehow.
If possible, I would suggest defining some kind of common type that can serve as input for the BuildWith method. For example, can the label string also be represented as a ParseObject? If not, can you think of some common abstraction for the two?
If the answer to both of these is no, that I would pose that these two methods probably shouldn't be overloads in the first place.
If the answer is yes, then you can make only one of these methods abstract:
public abstract class SpaceshipManager : MonoBehaviour
{
public abstract void BuildWith(ParseObject po);
public void BuildWith(string label)
{
// Static method or constructor here to represent label as a ParseObject.
BuildWith(ParseObject.FromLabel(label))
}
}
In this example, ParseObject is the common abstraction. It could also be another class or interface however.
Depending on the situation, the generics option that #Lee posted could also be a good solution, perhaps combined with a non-generic base type:
abstract class SpaceshipManager<T> : SpaceshipManager
{
public abstract void BuildWith(T source);
}
abstract class SpaceshipManager
{
// Other methods here
}
If neither of these solutions work for you, you could always make the method(s) virtual instead and override the behavior if needed, but it's somewhat doubtful that this design makes sense in your situation.
You can implement two Interfaces. IBuildWithFromString and IBuildWithFromParseObject. Then you can query which Interface is implemented by trying to cast to this Interface and in case of successand you can call the appropriate method.

Generics and inheritance... Getting around having to specify the <T> type?

Well, I've had to rewrite this as I've been down voted five times for giving too much detail... Go figure!
class BaseModel
{
public T[] Get<T>()
{
// return array of T's
}
public T Find<T>(object param)
{
// return T based on param
}
public T New<T>()
{
// return a new instance of T
}
}
class BaseRow
{
private BaseModel _model;
public BaseRow(SqlDataReader rdr, BaseModel model)
{
// populate properties of inheriting type using rdr column values
}
public void Save()
{
// calls _model.Save(this);
}
}
I currently have a number of classes that inherit the BaseModel class. Each of the methods exposed by BaseModel will return an instance, or an array of instances of a type that inherits the BaseRow class.
At the moment, when calling the exposed methods on the BaseModel via an inheriting class, i.e.
using(DeviceModel model = new DeviceModel())
{
DeviceRow row = model.Find<DeviceRow>(1);
DeviceRow[] rows = model.Get<DeviceRow>();
DeviceRow newRow = model.New<DeviceRow>();
}
I have to specify the type (a class that inherits the BaseRow class), as the methods in BaseModel/BaseRow do not know/care what type they are, other than they inherit from BaseRow.
What I would like to do is find a way to remove the need to specify the without having to replicate code in every class that inherits BaseModel, i.e.
class DeviceModel : BaseModel
{
public DeviceRow Find(object param)
{
return this.Find<DeviceRow>(param);
}
}
Note: Unfortunately I am unable to implement or use any third party solutions. That said, I have tried using Castle Active Record/nHibernate and to be honest, they are very big and heavy for what should be a very simple system.
Hopefully I haven't provided "too much" detail. If I have, please let me know.
Thanks
If I were you, I'd suggest making BaseModel a generic class. In a situation of "can't win either way", the code you've removed to make others happy might have told me more about what you're doing (not a criticism by any stretch - I appreciate your position).
class BaseModel<T>
{
public virtual T[] Get()
{
// return array of T's
}
public virtual T Find(object param)
{
// return T based on param
}
public virtual T New()
{
// return a new instance of T
}
}
That's your base, and then you have inheritors like:
class DeviceModel : BaseModel<Device>
{
public override Device New()
{
return new Device();
}
}
Now, any generic operations you define in DeviceModel will default to returning or using strongly typed Device. Notice the virtual methods in the BaseModel class. In the base class methods, you might provide some basic operations predicated upon using T's or something. In sub-classes, you can define more specific, strongly typed behavior.
I'd also comment that you might want to pull back a little and consider the relationship of BaseModel and BaseRow. It appears that you're defining a parallel inheritance hierarchy, which can tend to be a code smell (this is where more of your code might have come in handy -- I could be wrong about how you're using this). If your ongoing development prospects are that you're going to need to add a FooRow every time you add a FooModel, that's often a bad sign.

How to retrieve the argument of a generic base class at compile time? (i.e., without using Reflection)

I want to implement a generic method to retrieve header/detail data from a database:
public static T RetrieveHeaderDetail<T>
where T : Header<???>, new()
// Where ??? means "what can I do here?"
{
// ...
}
Here is the definition of the generic representing a document header:
public class Header<TDetail> where TDetail : class, new()
{
public List<TDetail> Details;
}
And here are some instantiations:
public class RequestForQuotation : Header<RequestForQuotationDetail> { ... }
public class Order : Header<OrderDetail> { ... }
public class Invoice : Header<InvoiceDetail> { ... }
// ..
It is not hard to prove that, since .NET does not allow either multiple inheritance or "generic specialization" (which would allow a Header<U> to derive from some other Header<V>), for any specific T, there is at most one U such that T inherits (directly or indirectly) from Header<U>. Moreover, it is trivial to find the type U: iterate over T's base types until you find an instance of Header<U>, and then just take the generic's argument! Still, C# wants me to specify the change my method's definition to the following:
public static T RetrieveHeaderDetail<T,U>
where T : Header<U>, new()
where U : class, new()
{
// ...
}
Is there any way to get around this problem? I know it would be possible using Reflection, but I think it is a good practice to never do at runtime what could be done at compile time.
When I hit problems like this, I really, really miss C++.
I asked this question not too long ago.
Generics with Generic Parameters and Abstract class
I'm not sure I fully understand what you're after, but could you define an interface and use it to specify the constraint?
For example, we have something like this in a couple places:
public class Reader<T> where T : IInt32Id
{
public T GetById(int Id)
{
// get by id
}
}
Then I just use IInt32Id as an interface to derive all of my classes that have an int (as opposed to long) ID field.

C# generics based object to object mapper question

I have the need for an object to object mapper in my application. I've tried out a few, but haven't been able to find anything that fits my needs, so I'm writing my own. Currently I have an interface like below:
public interface IMapper<T, R> {
T Map(R obj);
}
I then implement an AccountMapper that maps a Customer to an Account as:
public class AccountMapper : IMapper<Account, Customer> {
Account Map(Customer obj) {
// mapping code
}
}
This works fine so far, however I have several source entities that map to the same destination entity. For instance I have a Payment and an Invoice that both map to BillHistory. For the above to support this, I need to make two separate mappers (ie. BillHistoryPaymentMapper and BillHistoryInvoiceMapper), which is fine. However, I'd love to be able to implement it slightly differently like below. Only problem is I don't know if it's possible and if so, I don't know the correct syntax.
public interface IMapper<T> {
T Map<R>(R obj);
}
public class BillHistoryMapper : IMapper<Account> {
public BillHistory Map<Invoice>(Invoice obj) {
// mapping code
}
public BillHistory Map<Payment>(Payment obj) {
// mapping code
}
}
While the first implementation works fine, the second would be slightly more elegant. Is this possible and if so what would the correct syntax look like?
edit-------
I hate when people do this, but of course I forgot to mention one little detail. We have an abstract class between the mapper and the interface to implement some common logic across all of the mappers. So my mapper signature is actually:
public class BillHistoryMapper : Mapper<BillHistory, Invoice> {
}
where Mapper contains:
public abstract class Mapper<T, R> : IMapper<T, R> {
public IList<T> Map(IList<R> objList) {
return objList.ToList<R>().ConvertAll<T>(new Converter<T, R>(Map));
}
}
You'll have to use your first interface and implement the interface multiple times on your object:
public class BillHistoryMapper : IMapper<Account, Invoice>,
IMapper<Account, Payment> {
...
}
I would serious consider taking a look at AutoMapper instead of writing your own. There are a lot of nuances in mapping that it has already solved, not to mention it has been through plenty of performance testing, bug fixes, etc.
With regard to your abstract class consider getting rid of it and replacing it with an extension method. This will allow you to use the MapAll function regardless of whether you implement the interface or use some sort of inheritance chain.
public static class MapperExtensions
{
public static IEnumerable<TOutput> MapAll<TInput, TOutput>
(this IMapper<TInput, TOutput> mapper, IEnumerable<TInput> input)
{
return input.Select(x => mapper.Map(x));
}
}
This will now make it easier when trying to solve your problem above because you no longer have to inherit from a base class you can now implement the mapping interface for the types you want to map.
public class BillHistoryMapper :
IMapper<Invoice, BillHistory>, IMapper<Payment, BillHistory>
{
public BillHistory Map<Invoice>(Invoice obj) {}
public BillHistory Map<Payment>(Payment obj) {}
}
Also consider changing your IMapper generic parameters to be the other way round (I took the liberty in the previous examples):
public interface IMapper<in TInput, out TOutput>
{
TOutput Map(TInput input);
}
The reason for this is that it directly maps to the System.Converter<T> delegate and you can do something like:
IMapper<ObjectA, ObjectB> myAToBMapper = new MyAToBMapper();
ObjectA[] aArray = { new ObjectA(), new ObjectA() };
ObjectB[] bArray = Array.ConvertAll<ObjectA, ObjectB>(aArray, myAToBMapper.Map);
List<ObjectA> aList = new List<ObjectA> { new ObjectA(), new ObjectA() };
List<ObjectB> bList = aList.ConvertAll<ObjectB>(myAToBMapper.Map);
// Or
var aToBConverter = new Converter<ObjectA, ObjectB>(myAToBMapper.Map);
bArray = Array.ConvertAll(aArray, aToBConverter);
bList = aList.ConvertAll(aToBConverter);
AutoMapper has also been suggested which will make your life easier. However if you wanted to keep your mapping abstraction and have your code agnostic to your mapping strategy then it is very easy to use the above interface to inject a wrapper around AutoMapper. It will also mean you can continue to use the MapAll extension method explained above.
public class AutoMapperWrapper<in TInput, out TOutput> : IMapper<TInput, TOutput>
{
public TOutput Map(TInput input)
{
return Mapper.Map<TOutput>(input);
}
}
Final word
Also keep in mind you are not always going to find that your mapping strategy will work across the board so don't try to fight your domain and force it to fit your mapping strategy. One particular example is you might have to map from two input items into one. You can obviously make this fit your strategy but you may find it becomes messy. In this particular example consider it a merge.
Your second example will work with only a few changes:
// you have to include the R type in the declaration of the Mapper interface
public interface IMapper<T, R> {
T Map<R>(R obj);
}
// You have to specify both IMapper implementations in the declaration
public class BillHistoryMapper : IMapper<Account, Invoice>, IMapper<Account, Payment> {
public BillHistory Map<Invoice>(Invoice obj) {
// mapping code
}
public BillHistory Map<Payment>(Payment obj) {
// mapping code
}
}
I'm not sure if this actually gains you anything over the existing pattern, though.
If there is a limited number of types you want to map from, then I would use the first method of declaring the input and output types in the interface definition. Then a mapper can implement interfaces for each input type it supports, so your BillHistoryMapper would be declared as:
public class BillHistoryMapper : IMapper<BillHistory, Invoice>, IMapper<BillHistory, Payment>
{
...
}

Using Interface variables

I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).

Categories

Resources