In C#, it's possible implementing interface methods without making implementing method as public. For example,
void ITest.SomeMethod()
{
// ...
}
Is there equivalent for ActionScript3?
Nope. From the AS3 Language Spec:
Classes that implement an interface method must use the public attribute to implement all interface methods.
In ActionScript, there is no way to add access level qualifiers; however, this question has been asked here, leveraging inheritance of interfaces:
How to expose a method in an interface without making it public to all classes
Perhaps an internal class may be another approach; although, not recommended.
But directly no, all members of ActionScript interfaces are public.
Related
I know that an abstract class is a special kind of class that cannot be instantiated. An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but, it cannot be instantiated. The advantage is that it can enforce certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
Also I know that An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface.
BUT
BUT
BUT
I noticed that we will have Default Interface Methods in C# 8.0
Maybe I'm asking it because I have only 1-2 years of experience in programming, but what would be main difference between abstract class and interface now?
I know that we can't make state in interface, will it be only one difference between them?
Conceptual
First of all, there is a conceptual difference between a class and an interface.
A class should describe an "is a" relationship. E.g. a Ferrari is a Car
An interface should describe a contract of a type. E.g. A Car has a steering wheel.
Currently abstract classes are sometimes used for code reuse, even when there is no "is a" relationship. This pollutes the OO design. E.g. FerrariClass inherits from CarWithSteeringWheel
Benefits
So from above, you could reuse code without introducing a (conceptually wrong) abstract class.
You could inherit from multiple interfaces, while an abstract class is only single inheritance
There is co- and contravariance on interfaces and not on classes in C#
It's easier to implement an interface because some methods have default implementations. This could save a lot of work for an implementer of the interface, but the user won't see the difference :)
But most important for me (as I'm a library maintainer), you could add new methods to an interface without making a breaking change! Before C# 8, if an interface was publicly published, it should be fixed. Because changing the interface could break a lot.
The logger interface
This example shows some of the benefits.
You could describe a (oversimplified) logger interface as follows:
interface ILogger
{
void LogWarning(string message);
void LogError(string message);
void Log(LogLevel level, string message);
}
Then a user of that interface could log easily as warning and error using LogWarning and LogError. But the downside is that an implementer must implement all the methods.
An better interface with defaults would be:
interface ILogger
{
void LogWarning(string message) => Log(LogLevel.Warning, message);
void LogError(string message) => Log(LogLevel.Error, message);
void Log(LogLevel level, string message);
}
Now a user could still use all the methods, but the implementer only needs to implement Log. Also, he could implement LogWarning and LogError.
Also, in the future you might like to add the logLevel "Catastrophic". Before C#8 you could not add the method LogCatastrophic to ILogger without breaking all current implementations.
There is not a lot of difference between the two apart from the obvious fact that abstract classes can have state and interfaces cannot. Default methods or also known as virtual extension methods have actually been available in Java for a while. The main drive for default methods is interface evolution which means being able to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface.
another couple of good points mentioned by this post:
The feature enables C# to interoperate with APIs targeting Android
(Java) and iOs (Swift), which support similar features.
As it turns out, adding default interface implementations provides
the elements of the "traits" language feature
(https://en.wikipedia.org/wiki/Trait_(computer_programming)). Traits
have proven to be a powerful programming technique
(http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf).
Another thing which still makes the interface unique is covariance / contravariance.
To be honest, never found myself in situation where a default impl. in interface was the solution. I am a bit sceptical about it.
Both abstract classes and the new default interface methods have their appropriate uses.
A. Reasons
Default interface methods have not been introduced to substitute abstract classes.
What's new in C# 8.0 states:
This language feature enables API authors to add methods to an interface in later versions without breaking source or binary compatibility with existing implementations of that interface. Existing implementations inherit the default implementation.
This feature also enables C# to interoperate with APIs that target Android or Swift, which support similar features. Default interface methods also enable scenarios similar to a "traits" language feature.
B. Functional differences
There are still significant differences between an abstract class and an interface (even with default methods).
Here are a few things that an interface still cannot have/do while an abstract class can:
have a constructor,
keep state,
inherit from non abstract class,
have private methods.
C. Design
While default interface methods make interfaces even more powerful, abstract/base classes and interfaces still represent fundamentally different relationships.
(From When should I choose inheritance over an interface when designing C# class libraries?)
Inheritance describes an is-a relationship.
Implementing an interface describes a can-do relationship.
The only main difference coming to my mind is that you can still overload the default constructor for abstract classes which interfaces will never have.
abstract class LivingEntity
{
public int Health
{
get;
protected set;
}
protected LivingEntity(int health)
{
this.Health = health;
}
}
class Person : LivingEntity
{
public Person() : base(100)
{ }
}
class Dog : LivingEntity
{
public Dog() : base(50)
{ }
}
Two main differences:
Abstract classes can have state, but interfaces cannot.
A type can derive from a single abstract class, but can implement multiple interfaces.
There are some other, smaller, differences when it comes to default modifiers.
I am developing an internal class that implements an internal interface.
Can anyone explain why I cannot declare my method as internal, why I am getting the following error: "cannot implement an interface member because it is not public".
I know that I have to declare the method as public, but it makes absolutely no sense to me.
What is the point of declaring a method public if both the interface and the class are internal?
Is it not misleading?
I have read a related question on this site. It is not an exact duplicate, because my class is internal.
Simply put: because that's the way the language designers designed it. Even in internal interfaces, the methods are implicitly public. It does make things simple, but it's a pain in other ways.
If you want a public class where you want to "hide" the use of an internal interface, you could use explicit interface implementation - although that has other drawbacks.
Of course, if your class is internal then it doesn't matter that the methods are public anyway - other assemblies aren't going to be able to call the methods because they can't see the type.
I definitely agree that C# (or .NET in general) hasn't been designed as carefully as it might be around internal interfaces.
In terms of exactly why you're getting an error message - section 13.4.4 of the C# 4 spec (interface mapping) is the reason. Implementations are only found for nonstatic public members and explicit interface member implementations - and if there are any unimplemented members in the interface, an error occurs.
I know this is old but maybe someone find it useful. You can accomplish a kind of internal interface methods like this:
internal interface IFoo
{
void MyMethod();
}
public abstract class Foo : IFoo
{
void IFoo.MyMethod()
{
MyMethod();
}
internal abstract void MyMethod();
}
So all your internal classes should derive from Foo and are forced to implement the abstract MyMethod. But you can treat them all as IFoo of course. But those classes outside the assembly won't provide the MyMethod class.
So you have the advantage to treat your classes internally as IFoo and rely on MyMethod. The drawback is that all your classes will need to derive from Foo which can be a problem if you need another base class.
But I found it helpful if the abstract base class is a generic one and the interface is not. Maybe it is useful in some cases.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can't I have protected interface members?
as title, in C#. Is there no possibility that someone might want to have a protected or an internal interface?
Because Interface is in crude terms 'a view to the outside world' and since it is for the outside world, there is no point making its members protected or private.
Or in other words, it is a contract with the outside world which specifies that class implementing this interface does a certain set of things. So, hiding some part of it doesn't make sense.
However, interfaces themselves can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.
Interface members are always public because the purpose of an interface is to enable other types to access a class or struct. No access modifiers can be applied to interface members.
All the interface methods are Public. You can't create an access modifier in interface. If you want to use one, use Abstract class.
This is due to the nature of the interface. An interface, by definition is a specification.
A rule in .NET specifications dictates that a class that implements an interface will have to implement all members of that interface.
Now if we mark a member private, then the implementing class cannot implement that particular member.
Please see Non Public Members for C# Interfaces
Interfaces are Coding contracts, this is the very reason it won't allow any access modifier other then Public in it's Method signatures.
But an Interface by itself can be Internal but not private or protected, Internal allows access within the assembly which is perfectly fine.
Another translation question, this may be more theoretical, but I am curious as to the design choice. SFNQ:
Why does C# not allow controlling for controlling access to methods in interfaces like Java does? For example, in a C# interface:
public void Visit(Axiom axiom);
Thank you.
In C#, and .Net in general, all methods on an interface are public by default. There is no way to restrict their access.
Consider the alternative, what would it mean to have a protected member on an interface? How would you establish the access rules to allow or disallow a caller of an interface access to the particular method? (I mean protected in the C# sense, not the java one).
Even better, what would private mean?
In both C# and Java, all methods on an interface are public.
In Java, the public keyword is allowed, likely to save on parsing rules. In C#, the public keyword was considered redundant and was removed from interface declarations altogether.
In C# all members of an interface must be public, therefore it will not allow you to add any visibility modifiers to the member declarations. The public keyword is therefore redundant and not needed (infact if you include it you'll get a compiler error).
An interface is a contract which states that you will provide all of the functionlity specified in the interface definition. If you were allowed to have private members in an interface you would not be exposing that functionality (and you would therefore violate the contract).
I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).