0
abstract class VS interface
what is different between abstract class and interface?! somebody explain it simple
2 Antworten
+ 3
in C# a class can inherit only one class
but it can inherit many interfaces at once
this was made to separate interfaces and classes, though abstract classes and interfaces look really similar - they both can have methods, properties and you can neither create an object of an abstract class, nor of an interface. the difference is in concepts of these two things. i'll try to explain it
an abstract class is an idea of an object - "an animal", for example. inherited classes can be a cat, a frog - they are all animals. if there is another abstract class like "a car", its subclasses can be a ferrari, a bmw, and so on. but a cat can't be an animal and a car at once - no multiple inheritance in C#. that's it
interface is a way to communicate between different things. let there be an IMovable interface. all classes that have it must be able to move (you must be able to call a method Move() in all of them). let the cat class inherit it, the frog, the ferrari too. when you make the cat move, it runs, a frog jumps,
+ 2
a ferrari drives - these are different implementations of Move() method. if a bmw class doesn't inherit the IMovable interface, it can't move, and if you call this method on bmw, you get an error.
let there be another interface - ISoundable with a method Sound(). any class - a cat, a ferrari, literally any of them - can inherit BOTH IMovable and ISoundable. a cat can run and meow, a ferrari can drive and honk, so if you call Move() or Sound() on any class instance that inherits these two interfaces, it WILL move or make a sound.
i hope I made it clearer. i also highly recommend you to read about object-oriented programming. a decent explanation can be found in Bruce Eckel's "Thinking in C++" book (nevermind the C++ in title, OOP is the same everywhere)