I understand that the interface is used to decouple the abstraction from the implementation. As a very common example you will see with a List and an ArrayList.
List<String> interfaceList = new ArrayList<>();
You can swap out the List implementation with any other class that implements the interface.
Same thing with abstract classes. So is there a reason why you don't see this?
AbstractList<String> abstractList = new ArrayList<>();
What is the difference between the two?
I understand that a derived class can only inherit from one base (abstract) class, but can inherit from multiple interfaces. However, I also believe that inheriting from multiple interfaces should be avoided, as it typically means the class is trying to do too much.
So what is the difference? When would you use one over the other?
Videos
Abstract classes may contain function definitions yes, but if you make every function in the class abstract doesn't that essentially make it the exact same thing as an interface?
Obviously Interfaces are different in some capacity otherwise they wouldn't exist. What am i missing here? Why would you ever use an interface instead of an abstract class?
In terms of code, they're very similar, which often raises confusion like yours.
Conceptually, I think of it this way. When you inherit from an abstract class, you're saying that you are a type of the class. You have the same attributes.
When you implement an interface, you're saying that you do the things that that interface does.
In one sentence, abstract classes allow you to inherit state/variables/data, interfaces allow you inherit behaviors.
Abstract classes may contain function definitions
This answers your question.
if you make every function in the class abstract doesn't that essentially make it the exact same thing as an interface?
Yes.
Why would you ever use an interface instead of an abstract class?
Because a class can implement multiple interfaces, but only extends a single (abstract) class.
Hey everyone, thanks for dropping by, recently learnt about abstract class and interface at school.
In work experience, when would you use abstract class and interfaces vice versa, whatβs the benefit over the other?
Interface, for me it is wonderful because it is a contract and we need to implement all the method, makes the class implements the interface much easier to understand.
Whatβs your view and experience on the two? Thank you for your time
I have the question of what is the use case for each of the above. I understand how inheritance works and everything. No problems there.
What I don't get is where to use each. I've almost always just solved my problems with base classes.
Say I have this :
class a {
virtual void stuff() {}
}
class aa : a {
override void stuff() {}
}Why would I not want to go this route? If I don't need to override the method I can simply leave it as is and there should still be a working stuff method.
Where do I put an interface or abstract class? Are all three methods do be used in tandem?
Again, I don't struggle with how they work, I'm just asking why use them. Say I was building a big app with lots of inheritance. How would I set up my architecture in the "best" way possible?
The two concepts are very similar, which is why I'm confused on why you should choose one over the other.
I've been programming for eight years now and I have a few languages under my belt, but I've just realized that I don't really know when to use which of these tools over the other.
I have the general idea of "Abstract classes can be partial implementation, vs Interfaces you must define each method of an implemented Interface".
But for some examples, say you have a few classes for a simple game:
Entity which will have subclasses/ concrete implementations of "Player" and "Enemy".
What would be the best way to go about this?
Entity = Interface, Player & Enemy = Abstract/ normal classes implementing Entity?
Entity = Abstract Class, Player & Enemy = standard classes extending the Abstract Entity's functionality?
Perhaps this question can't be answered without further details on the Entity/ Player & Enemy classes, in terms of how they would be interacting/ if there's any default implementation for the Entity class, but if any sort of answer can be given for clarity, all would be appreciated.
Also, same thing would go for an example like:
Item = Interface or Abstract Class?
Consumable = Standard class implementing Item, or concrete extension of Abstract Item?
Same for Equipment/Equipable & Throwable? (for Items).
Again, I feel like this may just be something that requires messing around with, but any and all input is helpful!
EDIT: Formatting.
Interfaces are just fully abstract classes. It gets hidden from you since the compiler implicitly inserts the abstract keyword whether you write it or not.
Given that information, can you think of when one might be better than the other?
It really depends on how you need these things to be usable by code outside these various classes. Another user put it very well in a recent thread, saying that interfaces are a way of ensuring compatibility of use without the mess of inheritance.
If you only have two concrete classes (Player and Enemy) extending or implementing Entity directly, then it won't really matter whether Entity is an interface or an abstract class, but if you find that you have duplicated code between the two, then the use of an abstract class is indicated. If you later find yourself needing to use (and create) a concrete Entity whose implementation details are quite different, then (and only then) it is indicated to make Entity an interface and to rename the abstract class formerly know as Entity.
If you need two or more differing branches of the inheritance tree to be able to fill the same role, make the role an interface. If the role can only ever be filled by something from a certain family (branch) of classes, it's okay to only abstract to the level of an abstract class.
The deal with abstract classes is that they are abstract, you can define abstract methods and also concrete methods. Them being classes means that when creating new classes you are limited to extending only one per class.
Interfaces on the other hand define abstract methods and also concrete methods through what I now learned is another use of the default keyword (the one I knew was switch cases). Interfaces can also be functional interfaces which means support for lambdas. You can implement more than one interface in a class.
Now that we know that both abstract classes and interfaces provide both support for concrete and abstract methods, and that you can "subclass" more interfaces in one class as opposed to "subclassing" abstract classes, as well as lambdas support for interfaces, why would there be a use for abstract classes? It seems interfaces can do all that abstract classes can do but better.
Basically you want, if possible, to use interfaces wherever possible. The only difference between an interface and an abstract class, aside from classes only being able to extend one class, is that abstract classes can contain state. If you don't need to contain state it's better to use interfaces since a class can implement any number of interfaces.
So to answer your question:
It seems interfaces can do all that abstract classes can do but better.
No. Abstract classes can contain state, interfaces can't.
An example for using interfaces, abstract classes and concrete classes:
public interface UserDb {
void storeUser(User user);
default void storeUsers(User... users) {
for(User u : users) {
storeUser(u);
}
}
}
public abtract class AbstractUserDb implements UserDb {
protected List<User> users = new ArrayList<>();
@Override
public void storeUser(User u) {
users.add(u);
}
}
public class JsonUserDb extends AbstractUserDb {
@Override
public void storeUser(User u) {
super.storeUser(u);
new ObjectMapper().writeValue(users, "users.json");
}
}
Abstract classes can provide implementation of methods as well as just declarations, so they can provide common or base implementations for methods that may be used by many subclasses. Take a look at java.util.AbstractList, for example, which provides some base functionality to make it easier to implement the java.util.List interface. If you want to implement List, you don't have to actually implement all of the methods declared by that interface yourselfβyou can just extend AbstractList and implement the get() method, and the default implementations of all the other methods provided by AbstractList will work out of the box, using your get() method, to give you a minimal implementation of List.
In Java, interfaces are almost preferred for their flexibility. What cases would you use an abstract class? Iβm having trouble thinking of good heuristic to choose this. Is it best to think of it as a partial implementation?
I can think of the Abstract classes in the Collections API like AbstractList, which are like a skeletal implementation. Also HttpServlet and Verticle from vertx. In these cases it makes sense because you have only one implementation that can be extended.
If we can use abstract class for both abstarct and non abstract methods, why bother to use interface? Why to choose interface over abstract class?
I'm working on a project in Computer Science and interfaces are really tripping me up.
EDIT : I didn't get a chance to check during class because I was rushing to get my work done, but thanks guys!
An interface is a promise that the class implementing the interface is able to do something, without specifying exactly how the class should do it.
Different classes implementing the same interface may do that something in different ways, but they promise to do it in some way specific to that class.
For example, java.util.ArrayList implements List, and thus promises that ArrayList is an ordered list of elements that implements get(int index) and add(int index, Object o) and so forth.
So if you don't care what kind of list you have, just that you want an ordered list of elements, you use the interface List.
List in turn is a Collection, which is what you use if you have a collection of elements, and don't care how they're stored. All you know is that you have a collection that you can .add(Object) and find out how many there are, through .size(), and so on.
Collection in turn is an Iterable, which means you have a stream of elements, and you don't know or care how many or how they're stored, just that you can get them in some order specific to the implementing class, through .iterator().
And then there is java.io.Closeable. Any object implementing Closeable promises that it can be closed. You don't have to know anything else about the object, but if you want to close it, you can.
It can be a network stream, it can be an open file, it can be a database connection. It doesn't matter. If it implements Closeable, it promises that it can be closed, without you having to care how it's done.
Interfaces free you from having to know or specify exactly how something is to be done, when you shouldn't need to know or specify it.
http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
As always, GO TO THE OFFICIAL TUTORIALS FIRST, then ask questions.
Hi everyone,
I'm following the 10th part of mooc.fi course and i'm starting to get confused about Interfaces and abstract classes
I don't see the point of using them. If a class implements an interface, and his methods, why should i use it if i have to rewrite those methods into the class that implements it?
abstract classes confuse me more, because i can't imagine examples of when i can use them
In this course i've always thought of a way to implement stuff, but i can't find any use for these two last parts
Now that i'm doing the Comparable interfaces, it's even more confusing, because for what i've in my mind, i could just use the method "compareTo" without implementing any interface
Sorry if this looks dumb for you, but i'm just a beginner
I'm designing a window class for my renderer. I want to write it's public methods in a parent class, and then write the logic in children classes (one for sdl, one for glfw, etc). But I'm unsure about the differences between an "interface" class and an abstract class. I want to be able to write its methods, but I also want to be able to store a variable of type "Window" (which is actually a child class) use it normally. What do you guys think is the right tool for the job? I appreciate it
Edit: Thanks for the replies everyone. Honestly I just needed this post so I could write out my thoughts. Once I realized the problem, some YouTube videos and your responses really helped
It seems like interfaces are much more flexible. From what i see, an abstract class is works like a set of actions that can be triggered by different scripts? While an interface is more like a way you can make multiple things react to a certain input, and have them all react differently to it, right?
What is the purpose of each of these?
I'm reading up on some design patterns and I found the strategy pattern here: http://www.dofactory.com/net/strategy-design-pattern
In the example code an abstract class is being used and as far as I can tell an interface would be a better option. I think this because an abstract class allows you to have "common" code that anything inheriting it can use, but in this case there is none of this and it's literally just a virtual method declaration that has no code in it.
So why not use an interface, if you don't need to share any code or override a method?
/// <summary>
/// The 'Strategy' abstract class
/// </summary>
abstract class SortStrategy
{
public abstract void Sort(List<string> list);
}
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class QuickSort : SortStrategy
{
public override void Sort(List<string> list)
{
list.Sort(); // Default is Quicksort
Console.WriteLine("QuickSorted list ");
}
}
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class ShellSort : SortStrategy
{
public override void Sort(List<string> list)
{
//list.ShellSort(); not-implemented
Console.WriteLine("ShellSorted list ");
}
}I'm still learning, so I might be missing something obvious. What does r/csharp think to this, why would you prefer an abstract over an interface in this scenario?
This is how I'd do it using interfaces:
public interface ISortStrategy
{
void Sort(IList<string> list);
}
class QuickSort : ISortStrategy
{
public void Sort(IList<string> list)
{
Console.WriteLine("QuickSorted list ");
}
}
class ShellSort : ISortStrategy
{
public void Sort(IList<string> list)
{
Console.WriteLine("ShellSorted list ");
}
}Can anyone explain me the difference between abstract classes and interfaces, and when we can use them
Please explain to me why you would use an interface over an abstract class. Object interfaces is limited to public functions and it seems redundant when you can use abstract classes.
interface base {
function foo(myclass $bar);
protected bad_function(); //php coughs up error because it cannot do this!!!!
}Can be replaced by:
abstract class base {
abstract function foo(myclass $bar);
abstract protected function bad_function(); //works here....
}
class something extends base {
function foo(myclass $bar) {
//do something with $bar
}
protected function bad_function() {
echo 'i am here';
}
}So... why would you ever need to use an interface when an abstract class covers all functionalities of interfaces and some? The only case I see for using interfaces is if you need to extend a class while implementing an interface.