Interface and Inheritance - an Object Oriented Design Dilemma - java

I'm having trouble understanding when/why to implement inheritance and when/why to implement inheritance via interface. Please bear with me as I explain..
Let's say we have a parent class Animal and we wish to extend it with 3 subclasses: Dog, Cat and Mouse.
Suppose all Animals are able to eat(), sleep(), scratch() and move(). and Dog is able to pant(). With this knowledge we would proceed to add the first 4 behaviors to the Animal superclass and have Dog, Cat and Mouse extend Animal. We would also add the method pant() to the Dog class bec only dogs pant().
Now what happens if we wish to add another method called waggleTail() but only Cat and Dog exhibit this behavior. We cannot add this behavior to Animal bec then Mouse will also inherit the behavior (and Mouse doesn't waggle it's tail). An alternative is to add the method waggleTail() to both the Dog and the Cat classes but not to the Mouse class. This approach, however, does not make sense bec we would then violate the DRY principle (don't repeat yourself) by writing the method waggleTail() twice. We want to write each method once, and only once.
Perhaps we could solve this problem by creating a new sub class that inherits from Animal called TailWagglingAnimal, add the method waggleTail() to this subclass and then have both Dog and Cat inherit from this new subclass. This sounds reasonable until you realize that there are dozens of other such anomalies and we'd have to repeat this process again and again for each one (this would expand the inheritance hierarchy to no end).
Further, what if we have a specific kind of Dog (let's call him the "Coton de Tulear") that exhibits all of the other behaviors of Dog (such as panting) except that it doesn't waggle its tail. If we have "Coton de Tulear" inherit directly from Animal it would be unable to pant(). If we had it inherit from Dog it would be able to waggle its tail (bec Dog extends TailWagglingAnimal). If we had Dog extend Animal directly and then create a new subclass called TailWagglingDog (as appose to TailWagglingAnimal) then Cat will be unable to inherit this behavior (so we'd need to duplicate the behavior somewhere within the Cat hierarchy which violates the DRY principle).
What do we do?
Based on dozens of threads on stackoverflow (and several OO design books) it has been suggested to remove the method waggleTail() from the Dog class and add it to and interface. Let's call the interface TailWaggler and then have all dogs (except for "Coton de Tulear") implement this interface. However, I have trouble understanding why/how this is useful.
If you think about it, this means that all 50+ breads of dogs (let's assume there are 50 breads of Dog that need to exhibit this behavior) need to add the implements TailWaggler keyword just bec a single kind of Dog does not exhibit this behavior. Not only does this mean a lot of extra manual work on the part of the programmer (adding implements TailWaggler to the beginning of each class) it means that all descendants need to be concerned with all of little and petty details of the behavior they exhibit (this would not be the case had we added this behavior to the parent class and extended the parent class). This may be fine if we only had a few such cases but what if we had dozens or hundreds of such cases? Finally, as we add new types of subclasses of type dogs there will eventually be one kind of Dog are another that will not exhibit one of the behaviors of Dog parent class - so this means slowly but surely we'll need to remove almost all behavior from the (parent) Dog class and add them to an interface? We'd then need to make sure all of the sub classes implement dozens of different interfaces. One might suggest that we group all related behavior in a single interface but this is only possible if the behavior exhibited by different dogs is uniform - what if this is not the case?)
Thanks!

We'd then need to make sure all of the sub classes implement dozens of
different interfaces
If your class needs implementing too many interfaces check that it does not violate the Single Responsibility principle. Consider breaking the class into smaller ones.
Implementing several small interfaces instead of a large one conforms to Interface Segregation principle which leads to some positive consequences.
it means that all descendants need to be concerned with all of little
and petty details of the behavior they exhibit
This is more about implementation difficulties. Multiple inheritance or auto delegation could help here. Since we don't have either in Java we have to choose between other options:
Implement delegation manually for each class :(
Use Java 8 interfaces if implementation is not complicated.
Use code generation library to autogenerate delegation code (e.g. look at lombok library #Delegate feature https://projectlombok.org/features/experimental/Delegate.html)

Inheritance is used when you want to morph a class which is of the same type of your parent class and which have a similar behavior.
Interface is used to declare a functionality of your class.
For example, Dogs, Cats and Mice are all Animals (same type) and they have similar behavior (they get born, grow up, die, move, eat, ...). So your Dog class can extend Animal.
Now, your interfaces declare their functions. Like we just seen, an animal can move and eat, so your Animal class can implement the interfaces Mover and Eater for example. Automatically, Dog, Cat and Mouse will inherit these interfaces, but a mouse will eat cheese while dogs and cats will eat meat. This is where you can #Override (understand morph) the implementation behavior to declare what each class can eat.
If another animal can climb (a monkey), you will implement the Climber interface directly on the Monkey class. Making it slightly more evolved than a standard Animal.
For your tailwagging issue, you have to implement the Tailwagger interface in Dog and Cat, not in Animal (all animals are not tailwaggers). Of course you do not want to repeat the code, so you will also create another Class called StandardTailwag and use it as a field in Dog and Cat (composition). You then have to redirect the implementation to this class' methods, but this is the way to go if you want your code easier to maintain in the future.
You could also morph the StandardTailwag to DogTailwag and CatTailwag, and easily implement them with the same Tailwagger interface
Note that you can write default code and methods in Java 8's interfaces, but it is not recommended.

This is a very broad and subjective question, so I can give you my opinion and no more.
My personal principle is: "The less code you write, the better", but to be truthful achieving simplicity is exceedingly difficult.
I try to make inheritance as shallow as I can, because deep inheritance tends to become a problem later on when your model changes.
I then use interface with handlers so instead of having a method waggleTail I have a stateless TailWaggler class which does the waggling thing.
I don't think there is a recipe for every possible situation, I try keep it as simple as I can, as testable as possible, then you will have (sooner or later) to refactor your code, if test are good, it will not be too painful.

Short answer to a long question, so don't accept this until others that have more energy chime in. BUT how I would do that would be to have an abstract Dog class that implements the TailWagger interface, and has a concrete tailWag function.
Next have all your dogs inherit from Dog, including the one that doesn't actually wag. Then in that particular dog implementation, create a new concrete function called tailWag that throws an exception along the lines of InvalidStateException("This type of dog does not wag its tail") .
Using this methodology, you have one concrete "tailWag" that wags the tail, and one exceptional case that behaves differently.

Related

Best way to apply inheritance and code reuse

I have a question regarding the best way to structure code for reuse with inheritance in cases, where some methods in the base class does not make sense in the inheriting class.
I think this is a general OOP issue and not only peculair to TypeScript...
So basically, in some form of pseudo code, the issue is similar to this:
class BaseClass
makesSenseForA
makesSsenseForA
....
doesnotMakeSenseForA
doesnotMakeSenseForA
....
How then to have a Class A inherit BaseClass. Just direct inheritance means that Class A would have member methods that does not really make sense.
Not using inheritance means the things that code would be duplicated in both BaseClass and Class A
Moving the makesSenseForA methods to an external class and have both BaseClass and it's children class depend on this extracted class (ie using composition) does not work in this particular scenario, because the extracted class should actually be seen as A BaseClass.
How really is the best way to handle this kind of OOP modeling situation?
EDIT:
For lack of better example, it is like trying to model Human and Cyborg - this two would share a ton loads of similar implementation and hence first thought might be to have Cyborg extends Human...
But also there would be a ton of implementation that Human has that Cyborg should not have.
Doing away with inheritance means those similar functionality would have to be duplicated in Human and Cyborg`.
And composition also does not work, because if you extract those implementation that are similar into a separate object, that object, and it's method would have a property of Human, and hence should be seen as a Human in our modelling.
Yes, it indeed is a common issue. But your example isn't a very accurate reference to inheritance. We mostly use inheritance not due to common functions. Common functions, to reuse them, can be written as utilities/utility classes. You inherit a class when it is basically a sub-type of the parent class, and we create interfaces for things that are not actual objects but a type. For example:
Interface: Animal
Class: Tiger implements Animal
Class: Goat implements Animal
Note than Animal as such cannot be objectified. Now even though a lot of the functionalities of both classes Goat and Tiger will be common, but neither should extend the other, since a method hunt() will not make sense to the Goat class, and graze() won't make sense for Tiger. For that, we use interfaces. Now, to move common functions in the same class, you can further break this modularity as:
class Carnivore extends Animal
class Herbivore extends Animal
No brownie points for guessing what Goat and Tiger will implement now. In case, there are common functions, that you cannot for some reason write in the Animal class, you can write them as a utility. Suppose you have a robotic goat, that has a lot of common functionalities with an actual goat, you do not extend Goat, but move common functions as a utility, say GoatUtilities.
Edit: Someone pointed out that utility classes aren't exactly OOP but procedural... But they can definitely compliment your classes to help them follow OOP the correct way. That's why they're "Utility" classes. So, here's the point that got missed, what I tried to point out basically was how inheritance was being misinterpreted / misused in the given example that was in a way leading to the issue that kinda violated OOP principles. Having a viable object oriented design doesn't imply that you shouldn't use utility classes, because the objective is to apply inhertence and code reuse.
If you're making the method private it will only be usable in that class. If you make it protected it will be usable in all sub-classes too. So the methods that make no sense in Class A should be private, the others should be protected or public.
In java you can learn about this further here.

Interfaces without methods vs fields

I have two classes, LivingCreature ,and Animal which inherits from it.
I want to implement a class for each existing Animal, but since different animals share lots of features, I want to be able to classify Animals into several categories:
Flying, Walking, Swimming, Carnivore, Vegeterian and so on...
Every animal can reside in several, even from the same area, for example Flying, Walking and Carnivore.
Also, each category may hold several unique attributes, for example a flying animal should consist speed and eating type (e.g. whether it sits on a tree picking worms, or "raiding" the earth and picking animals with its legs)
The First thing that I definitely want to avoid is to hold a different set of fields for each concrete animal implementation.
Now, since some categories are simply binary (Carnivore or Vegan) and some are definitely not, I wonder what would be the right way to implement it.
I tend to go towards interfaces for each category, even if they won't be holding any methods , but I'm encountering a conflict:
It looks odd to hold an interface for such simple use like isMeatEating which holds a single boolean field.
On the other hand, having several categories as Animal's fields and several others implemented as Interfaces, sound very wrong and confusing.
What would be the correct/best option here, design-wise? (Perhaps there's a
design pattern which matches this use-case)
The pattern that you seem to describe is that of a trait or perhaps a mixin.
Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes.
Some languages, like Scala, have built-in support for these concepts.
In Java 8, with the help of default methods, we can do traits to some extend, and I say so, because that is not the reason why default methods were designed.
Now, it is hard to suggest ideas on your design without having full details of what you're doing, but I'll try to give an example of how I see it from my perspective.
Let's focus on eating profiles: carnivores vs herbivores. Carnivores eat other animals, herbivores eat plants or things of vegetal origin and omnivores may eat both. Both animals and plants are edible materials.
interface Edible {
Collection<Nutrients> getNutrients();
}
interface Vegetal extends Edible {}
interface Animal extends Edible{}
All animals eat, so we could define animal as:
interface Animal<T extends Edible> extends Edible {
Stomach getStomach();
Collection<Bolus> masticate(T food);
default void eat(T food) {
Objects.requiresNonNull(food, "The food must not be null");
for(Bolus bolus : this.masticate(food)) {
this.getStomach().ingest(bolus);
}
}
}
Spare me the details of Stomach and Bolus, and let's just assume all animals have a stomach and a way to masticate the food, turn it into a bolus and ingest it into their stomachs.
Now, we can finally reach our definition of:
interface Carnivore extends Animal<Animal> { }
interface Herbivore extends Animal<Vegetal> { }
interface Omnivore extends Animal<Edible> { }
Now you can define a
class Chicken implements Herbivore {}
class Lion implements Carnivore {}
class Bear implements Omnivore {}
Now a Chicken can only eat things of Vegetal type, and Lion only things of Animal type, whereas Bear can eat any Edible thing.
The more details I put on the default methods of my interface Animal, the less details I will need to implement in these classes and tha'ts, perhaps, a way to accomplish what you want.
I am aware that I may have not been able to answer your question, but I hope I have at least given you some ideas of where you can continue your investigation and experimentation of the ideal solution.

Interfaces and methods in Java [duplicate]

This question already has answers here:
Is there more to an interface than having the correct methods
(17 answers)
Closed 7 years ago.
For Java!!
We can implement different methods in different classes. In interface we create an abstract method and provide its implementation in the class that implements the particular interface. What is the purpose of creating an interface if we can create and implement methods in classes separately?
Plz help me I'm new in Java?
Consider an example :
Suppose you are creating some application which is concerned with the animal kingdom.
Now you are asked to create a dog, cat, lion etc objects.
So first thing will come to your mind, since these all belong to animal kingdom I can create a base class named ' Animal ', and everything will inherits it. Now yo created something like this
class Animal {
legs;
family;
eat();
roam();
sleep();
makeNoise();
}
So all the animals inheriting the animal class will have these features. You can call this as a "IS-A" relationship. Like Dog IS-A Animal.
Now suppose you are asked to use your animal simulation program for some science-fair. You can use this design in that too.
Now suppose someone asked you to use your simulator in a pet-shop.
Since you don't have any pet behavior. What you did is add the pet features in the base class and thought this will work.
So now you program can create a lion which has the pet behavior. STRANGE!!
Now what you need to put all the pet behavior in one place and make sure that all the pet animals should posses it.
A way to do is create another superclass with all pet features and extend it. This is multiple inheritance, which JAVA don't allow (just Google deadly diamond of death). So comes the interface.
Interface is more like a set of behaviors which your object implements.
And since every object can have its own set of implementations, all these methods should be abstract.
It gives you polymorphic benefits without deadly diamond of death problem. It is a more like a contract which defines that your object must implements following features.
So now what you can do
interface PetBehavior{
befriend();
play();
}
and classes from different inheritance tree can implement this interface.
We do that in order to organize data. This the ability to perform operations lots of times and to structure your data. There is another thing called Vector. If objects implement the same method, they can be iterated and sorted via this Vector
Because with a single interface you can have multiple implementation.
For example if you have a list interface, implementation could be ArrayList or LinkedList.
They have different performances and are used based on the context. By having the same interface, if you want to change something you have to simply change from this
List<String> arrayList = new ArrayList<String>();
to this
List<String> arrayList = new LinkedList<String>();
bacause they have the same methods but implemented in different ways
I used to have this question too!
There are 3 main reasons why we need interfaces:
it makes more sense. Interfaces create a "can be used as" or "have the ability to" relationship between the implementing class and the interface. For example, you can have an interface called Flyable and all the things that can fly implements this interface. E.g. Bird, airplane and balloons. These implementing classes "have the ability to fly" because they all have a fly method or whatever is defined in the interface. Also, if a method requires a Flyable object, the programmer can just pass in a bird, an airplane, etc. with his/her common sense. But still, this isn't very practical, just like whether you should write the { on a new line doesn't matter.
It makes it easier for you, and other programmers using your API or library or whatever you are creating, to create custom behaviors. Java Swing is a very good example. If you don't know what swing is, it is an API used to create programs that has a "window" or GUI. How are you going to tell the computer what to do when the user clicks on a button? Via an interface! There is an interface called ActionListener. It let you create your own things to do when the users clicks on a button. You just pass an ActionListener object to a method, with your own implementation, and it will be run when the button is clicked! If my words don't make sense, let me use one sentence to summarize all this.
interfaces provide a way to pass around different methods (with custom implementations) as parameters in methods.
EDIT
Oh I missed one point!
interfaces aid polymorphism. Say you have a dog, a cat, and a fish class and all of them don't implement any interfaces but have similar methods (move, sleep, eat etc). If you want to create an array of all your animals, you can only create an array of Object because all Java classes inherits Object. This is unsafe because then you can add whatever you want into the array, and you need to do casting in order to use those move sleep eat methods. So sad! :( If you create an interface called Animal which contain the three common methods and make all three classes implement it, you can just create an array of Animal. And you don't even need to cast it to the right type before you can access move sleep eat! How cool is that!
So remember to create interfaces when a lot of your classes have similar methods but different implementations to just UNITE THEM ALL!

Subclass-specific code - should I use abstract base class methods or an interface?

I have a super-class, Animal, with two subclasses, Cat and Dog. Dog and Cat both need to have specific methods for speaking and moving. Here are two alternatives for achieving this:
Animal will have two abstract methods, move() and speak(); Dog, Cat and Dog each override the two methods so they are specific to them.
I could have an interface that has generic animal methods move() and speak(), with the two subclasses implementing the methods so they are again specific to them.
Is one of these approaches more appropriate than the nother? I realize if I had an ArrayList of animals, I would write:
ArrayList Animal<allAnimals> = new ArrayList <Animal>():
allAnimals.add(new Dog());
allAnimals.add(new Cat());
//If I override the methods, I can simply go:
for (Animal a: allAnimals) a.move();
//Where as if I implemented the methods, I would not need be able to do this. I would need to cast the animal as its specific animal. e.g. If I knew the animal was a dog.
Dog aDog= (Dog) a;
a.move();
So overriding and implementing could have certain advantages and disadvantages depending on the situation they are used in. Can anyone else elaborate on this ?
First, from the subclass point of view, there is no difference between overriding or implementing a method. So, the code that you wrote would work exactly the same in all cases (in Java, all methods act like C++ virtual functions; the method invoked is the one of the actual class being referenced).
So, the decission is to define a superclass that is an interface, an abstract class, or a instantiable class.
The instantiable class should be used if there makes sense to create objects of the superclass (new Animal()).
The abstract class, when there are no objects of the superclass but the implementation of some methods will be shared by all (or nearly all) the subclases.
The interface, when you only define the contract and the implementation is left to each subclass.
It depends of the scope of the problem to decide which use. For example, if move() just means "change x,y coordinates of animal", probably it should be an implemented method in an abstract class. But if you have to define how the animal moves, then Animal would be better an interface so each subclass defines it.
As a general rule of thumb, use extension (abstract classes), if and only if your extending classes will share a good amount of behavior. In that case, extension can be used eliminate the need for duplicate code, which is A Good Thing (TM).
On the other hand, if your classes simply need to have the same signatures, then go with an Interface, which is much more flexible (you can, for instance, implement several interfaces, but you can only extend from one class).
This is just somewhat generic advice, since every use case is different.
To avoid the limitations of extension, there are other techniques that can be used, for instance, composition: (http://en.wikipedia.org/wiki/Composition_over_inheritance).
Last but not least, I think you're slightly mistaken in your code.
You can call the methods on the base classes in exactly the same way, no matter if they're inheriting them from an Abstract Class or an Interface.
In this case it probably depends on whether or not you'd like to have a default implementation of move() so Dog and Cat don't HAVE to provide their own implementations. Presumably the move() method shares a lot of commonality between cats and dogs so you'd have better reusability with a common implementation in the superclass.
//Where as if I implemented the methods, I would not need be able to do this. I would need to cast the animal as its specific animal. e.g. If I knew the animal was a dog.
Dog aDog= (Dog) a;
a.move();
No, you wouldn't have to do this at all. If Animal is an interface instead of an abstract class, the process you show for abstract classes would work just fine.
Conceptually, an abstract class describes what the thing IS, an interface describes what it DOES. In this case it's appropriate to have Animal as an abstract class because a Cat or a Dog IS an Animal. Functionally, choose whichever option results in the least amount of coding / the cleanest class hierarchy.
In general, the rule of thumb is to use an interface if you can cause a Java class can implement many interfaces but extend only one class.
Extending (inheritance) should be used only if there is a lot in common to a few classes and you want to be able to reuse the same code.
By the way, in the code that you provided as an example, you can use:
for (Animal a: allAnimals) a.move();
both in the case when you use interface as well as inheritance.
First of all, you have a third option, which is: Have an interface (say, MoverAndSpeaker; although that's kind of a lame name), and have the abstract base class Animal 'implmenent' it:
static public abstract class Animal implements MoverAndSpeaker {
#Override
public abstract void move();
public abstract void speak();
}
Why would you even want something like that?
Unlike some of the answers here, I believe semantic consistency is the paramount consideration, and issues such as avoiding code duplication are either resolved on their own or take the minority in importance.
If I were in your position, the key criterion I would apply is:
"Are there objects which move and speak, which are not Animals?"
If the answer is "no", then moving and speaking is something Animals do. Thus, use the abstract methods only
If the answer is "yes", then I ask myself
"Do all animals move and speak?"
If the secondary answer is "yes", then use the above code (assuming you don't want some default implementation for all animals).
If the secondary answer is "no", consider just the interface. Although you might want an intermediary class between Dog, Cat and Animal - if you have some shared code or fields between all Animals which also move and speak.
Finally, if there's nothing in common to all animals, then as suggested in other answers, you might not need the Animal base class at all.

Achieving multiple inheritance via interface

I am a beginner in interface concept.
when I surfing for the information about "Achieving multiple inheritance via interface", I came across this link.. Multiple inheritance
I have a same doubt as the programstudent had.
hi, Good Explanation very much helpful In the uml diagram for java
there is no connection to Animal from Bird and horse why? Is it
necessary to use the implement the same method in the derived class
and why
void birdNoise();
void horseNoise();
why in the Peagus class
public void horseNoise()
{
System.out.println("Horse Noise!");
}
public void birdNoise()
{
System.out.println("Bird Noise!");
}
why this must be there? Why "Remember, we must write each class's own implementation for each method in the interface. reason? Thank for this good explanation Thank you
In that post, they have used multiple inheritance in c++ and converted to interfaces in java.
1.what I thought about inheritance is having some methods in parent class, and whenever the same methods are needed in other class(es) too, then those class(es) will inherit the parent class and use it.
But in interface concept if each derived class(es) has to define its own implementation then what is the use of inheriting it?
2.If we have to provide own implementation then why not we define that method in the derived class(es) itself. What is the use of inheriting it?
Someone please explain.
Thanks in advance.
When I switched from c++ to java I had this same feeling but now that I been working with java for a while it all kinda makes sense.
1.what I thought about inheritance is having some methods in parent
class, and whenever the same methods are needed in other class(es)
too, then those class(es) will inherit the parent class and use it.
Like the original author did, you can still do multiple inheritance in java you just must use interfaces. Interfaces are like pure virtual classes in c++.
But in interface concept if each derived class(es) has to define its
own implementation then what is the use of inheriting it?
The reason you implement an interface in java is so that you guarantee that class has those methods. That way you can have a specific class implement a generic interface and then treat every specific class that implements that generic interface the same.
Java Design is a bit different then c++ design but after doing several java program's you will become just as good at using multiple interfaces as you are at using multiple inheritance.
Each subclass has to define it's own implementation because each subclass may perform the operation slightly differently. Consider the following example:
public interface animal {
//All implementers must define this method
void speak();
}
This interface states that any Animal MUST have a way to speak. Basically, any type of animal is going to be able to make a noise. We then have 2 subclass, or 2 different types of animals that we create.
public class Dog implements animal {
//Define how a Dog speaks
public void speak() {
System.out.println( "woof" );
}
}
We then define another animal, cat
public class Cat implements animal {
//Define how a Cat speaks
public void speak() {
System.out.println( "meow" );
}
}
In this example, both Cat and Dog are animals, and therefore must be able to speak due to our interface. However, everybody knows that cats and dogs make different sounds. By allowing each subclass to define how it 'speaks', we can give Dog and Cat their own respective sound when the speak() method is called, while ensuring they are both Animals.
In answer to your question more specifically, inheritance forces it's subclasses to have a specific method. In other words, an interface states that "all my subclasses will define each of these methods". What this allows us to do is to write code that deals with the methods in an interface without knowing the specific subclass. We can safely do that because we know that each subclass MUST have defined the method in the interface class. If only the subclasses that use the method defined it, then we would have no way of knowing for sure whether it is safe to call the method on all subclasses.
Just a note: If you do not want a subclass to define the method, you can simply define an empty method like this:
public class MuteAnimal implements animal {
//A MuteAnimal can't speak!
public void speak() { }
}
Inheritance is often useless without polymorphism. It is really not easy to explain it all just in few sentences. My advices would be to look at interfaces for defining behavior (something like can-do relationship), and concrete inheritence for is-a relationships.
In the center of everything as you may learn is something called Single Responsibility Principle. This means that one class has one responsibility, if you are having more of them, you separate the class.
If you take your example, even the Pegasus isn't both horse and bird at the same time 100% percent. It would inherit the horse, but implement specific characteristics of the birds, which would be defined in interfaces, like Flyable for instance. You can say that birds have one way of flying common to them all, so inherit them from Bird. Pegasus is a little different, so that custom logic can be defined after you implement the Flyable interface with method Fly.
Also, the example with horseNoise and birdNoise is little unrealistic, you want one method speak() which will due to internal class alhorithm perform certain action. What if that pegasus could talk? Would you have a method for each word?
Back to Flyable example, say you now have a video-game. Now you can have polimorphism for this: Lets say that in game earthquake happens. You want for each animal that can fly to go and fly. You have a collection of animals currently in game, so you write this:
foreach(Flyable flyableAnimal in animals)
flyableAnimal.Fly();
You just rely on polimorphism ...
These were just some random thoughts, you can find far better examples online, hope this helps ...
If class A inherits from class B, that effectively means two things:
Class A can implicitly use all methods and properties of class B, and need only define that functionality which is in fact unique to class A.
Code which expects an object of type B will accept an object of type A.
Those two features of inheritance are in some sense orthogonal; one can imagine places where either could be useful without the other. Although derived classes can only have one parent class from which they gain implicit access to methods and properties, they may define an arbitrary number of interfaces for which they are substitutable.
Note that while some people insist that interfaces form a "has-a" rather than "is-a" relationship, I think it's better to think of them as saying something "is __able" or "is a __er", the point being that interfaces don't just define abilities, but define substitutability (i.e. "is a") in terms of ability.

Categories