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.
Related
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.
I had an interview where interviewer asked me first what is the difference between abstract class with all the methods abstract and an interface.
I replied that if it is required to inherit something in the future you will not be able to do it if you have already extended a class.
Then, he stated that it was a situation where one would never have to extend any other class and you have to implement a contract. In this circumstance, which would be better, an abstract class or an interface?
I told him you can use either of them but he was not satisfied. I could not understand why - I believe that is a developer/design choice.
The answer stating that an interface represents a contract is not acceptable.
That's the answer we give to Junior since it may be too complex to clearly figure out the difference between the essence of an abstract class and the essence of an interface without much architecture experience and without reading a lot of classic books about.
Any abstract class with public methods acts as a contract, as well as an interface.
An abstract class that doesn't provide any implementation is in 99% of cases a representation of an object's Role.
An interface represents a Role.
Each object might have several different roles that shouldn't be tied together but composed by the concerned object.
I'm explaining this with this example:
Your interviewer could say:
I have a Robot that can walk and a Human that can walk too.
So based on this case, he asks you: should I extract the walking feature in an abstract base class or in an interface, knowing that the implementations have nothing in common?
You think..."oh I know so: in this case, having one abstract class with an abstract method walk(), then is clearly the same than declaring an interface with the walk() method."
So your answer would surely be: "it's the choice of the developer !".
And it's really not an always valid answer.
Why? Let's see the next expectation:
A Human can eat, but obviously the Robot cannot and even doesn't need.
What if you implemented the walking feature with an abstract class? You would end up with:
public abstract class Biped {
public void abstract walk();
}
public Robot extends Biped {
public void walk() {
//walk at 10km/h speed
}
}
public Human extends Biped {
public void walk() {
//walk at 5km/h speed
}
}
How could you plug the eating feature? You're stuck because you can't implement it in the Biped base class since it would break Liskov Substitution Principle, since a Robot doesn't eat!
And you can't expect Human extending another base class due to the known Java rule.
Of course, you could add a specific Feedable interface only dedicated to Human:
public interface Feedable {
void eat();
}
Signature becomes: public Human extends Biped implements Feedable {
Clearly, it makes no sense and confusing to have one role implemented through a class and the other through an interface.
That's why starting with interface is really preferred whenever we have the choice.
With an interface, we can model Roles easily by composing.
So the final solution would then be:
public interface Walkable {
void abstract walk();
}
public interface Feedable {
void eat();
}
public Robot implements Walkable {
public void walk() {
//walk at 10km/h speed
}
}
public Human implements Walkable, Feedable {
public void walk() {
//walk at 5km/h speed
}
public void eat(){
//...
}
}
Doesn't it remind you the Interface Segregation Principle? ;)
To sum up, if you specify an IS-A relationship, uses an abstract class.
If you realize that you are about to model a Role (let's say a IS-CAPABLE-OF relationship), go with interface.
Here are the differences:
A class can extend exactly abstract class, but can implement any number of interfaces.
An abstract class can have protected, private (does not apply to your question), package, and public methods, but an interface can only have public methods.
An abstract class can have instance variables (often called data members or properties) while an interface can only have static variables.
The answer to the question: "blah never extend blah implement contract blah" is this: "I would use an abstract class if I did needed instance variables and/or non-public methods and otherwise I would use an interface".
Interfaces are the natural way of creating a contract because they force you to implement the methods they define.
Besides that, you can implement as many as you want in the case you want to add new interfaces to your class.
I can't say what your interviewer had in mind, but an interface is more of a "contract" whereas an abstract base class, while it can play that role too, is more geared towards hierarchies or IS-A relationships. E.g. an Apple IS-A Fruit, a Pear IS-A Fruit, etc. But you're right, they could well be used interchangeably for practical purposes in that context, but an OO purist might not want to use an abstract class unless they were expressing IS-A relationship(s).
One thing to keep in mind is be the ability to have diamond inheritance for interfaces.
Consider this interface hierarchy:
interface Base{}
interface Sub1 extends Base{}
interface Sub2 extends Base{}
interface SubSub extends Sub1, Sub2{}
The same wouldn't be possible with abstract classes:
abstract class Base{}
abstract class Sub1 extends Base{}
abstract class Sub2 extends Base{}
// NOT ALLOWED! can only extend one class
// abstract class SubSub extends Sub1, Sub2{}
This is something that would be allowed in C++ (although tricky to get right). I think he might have been fishing for this. In general, this is the ultimate reason why I always try to write interface hierarchies instead of class hierarchies.
For the first situation i'd chose interface over abstract class with all methods abstract as having interface leaves me with option in future for my implementing class to extend some other (abstract) class.
For second scenario, if you really don't want your concrete class to extend any other class and also want to "implement" contract, you can have abstract class with all methods abstract.
I can see such question was already answered. BTW, I would like to share what I consider the best explanation I have read so far.
The bellow text was copied and pasted from Deshmukh, Hanumant. OCP Oracle Certified Professional Java SE 11 Programmer I Exam Fundamentals 1Z0-815: Study guide for passing the OCP Java 11 Developer Certification Part 1 Exam 1Z0-815 (p. 319). Enthuware. Edição do Kindle.
13.2 Distinguish class inheritance from interface inheritance including abstract classes 13.2.1 Difference between Interface and Abstract Class ☝
"What is the difference between an interface and an abstract class" is usually the first question that is asked in a Java "tech-check". While being a simple ice breaker, it also an excellent question to judge a candidate's understanding of OOP. Candidates usually start parroting the technical differences such as an interface cannot have method implementations (which it can, since Java 8), while abstract class can. An interface cannot have static methods (which it can, since Java 8) or instance fields while an abstract class can and so on. All that is correct, but is not really impressive. The fundamental difference between an interface and an abstract class is that an interface defines just the behavior. An interface tells you nothing about the actual object other than how it behaves. An abstract class, on the other hand, defines an object, which in turn, drives the behavior. If you understand this concept everything else about them will fall in place. For example, "movement" is a behavior that is displayed by various kinds of objects such as a Car, a Cat, or a StockPrice. These objects have no commonality except that they move. Saying it the other way round, if you get an object that "moves", you don't get any idea about what kind of an object are you going to deal with. It could be a Car, a Cat, or a StockPrice. If you were to capture this behavior in Java, you would use an interface named Movable with a method named move(). On the other hand, if you talk about Automobile, a picture of an object starts forming in your head immediately. You can sense that an Automobile would be something that would have an engine, would have wheels, and would move. You intuitively know that a StockPrice or a Cat cannot be an Automobile even though they both do move. An abstract class is meant exactly for this purpose, when, once you identify a conceptual object, you do not need to worry about its behavior. The behavior kind of flows automatically. If you create an abstract class named Automobile, you are almost certain that it would have methods such a move, turn, accelerate, or brake. It would have fields for capturing inner details such Engine, Wheels, and Gears. You get all that just by saying the word Automobile. From the above discussion, it should be clear that interfaces and abstract classes are not interchangeable. Even though an abstract class with no non-abstract method looks functionally similar to an interface, both are fundamentally different. If you are capturing a behavior, you must use an interface. If you are capturing a conceptual object, you must use an abstract class.
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.
I've been using this tutorial to look into the Strategy pattern. I receive the output he talks about, but it seems like there is no option to use the digHole() method. When I call the method in the Dog() constructor it works though.
My guess is this happens because I need to implement a way to save the ability to dig in the Animal class (like the flying ability), am I correct in this? Does this also mean that for every action I want an animal to take, I should compose it in the Animal class, create an interface with the ability and then create two classes who implement that ability, meaning the ability is either implemented or it isn't?
I also have some troubles with formulating the main thought behind the Strategy pattern. Currently I'm looking at it as 'Encapsulate all actions and compose them together in one main class'. How accurate/fitting is this?
public class Animal {
public Flies flyingType;
public String tryToFly() {
return flyingType.fly();
}
public void setFlyingAbility(Flies newFlyType) {
flyingType = newFlyType;
}
}
public class Dog extends Animal {
public Dog() {
super();
setSound("Bark");
flyingType = new CantFly();
}
public void digHole() {
System.out.println("Dug a hole");
}
}
public interface Flies {
String fly();
}
class ItFlies implements Flies {
public String fly() {
return "Flying high";
}
}
class CantFly implements Flies {
public String fly() {
return "I can't fly";
}
}
I also have some troubles with formulating the main thought behind the Strategy pattern
Perhaps the best way to wrap your head around the Strategy pattern is to compare it to the Template method. Click on the links for the wikipedia articles.
Both involve certain design decisions up front in the base class, but when it finally gets down to specifying the different behavior for the various subclasses, the template pattern relies on inheritance - overriding an abstract method defined in a base/super class.
The strategy pattern relies on composition - the behavior (flying, digging) is itself an object which can be created independently and then injected into object of interest.
In a language like Java, once you override a method in the base class and then create an instance of the object, that behavior can never be changed. If that's how you want your object to work - great use inheritance. However if you don't know until runtime which behavior you will need, then it's worth the extra effort to design using the strategy pattern.
meaning the ability is either implemented or it isn't?
Although the tutorial you are referencing is rather clever, it's not a great model for using the strategy pattern. Adding the ability of flying to a dog is so counter-intuitive that it distracts from the lesson. With the strategy pattern there is no limit to the number of possible implementations of the algorithm of interest.
If you really want to stick with the Animal model, you might try more universal concepts like findFood, escapeFromPredator, findMate, raiseYoung - things which are meaningful to all animals but are not going to be exactly the same for every animal instance. Two different dog's might raiseYoung quite differently or do so differently over time so the strategy may need to be swapped out as the animal simulation continues.
Do I have to compose every method in my main class
You can, but you do not have to if it gets too tedious - to simplify usage of your classes you can have each object instantiate an appropriate strategy in it's own constructor. Then you have your choice - create the object and use the default behavior or replace the default behavior with another depending on the application.
Just create abstract method in Animal, so the Animal class become abstract too, but we don't care because what's is an animal in general, that's had no sense.
And in each class who inherits Animal define an implementation of this method.
This is not the pattern strategy, but I think it's one of the good way to do what you want (like I understood it)
The idea of the pattern strategy as I understand it is that the subclasses define the same kind of behaviour in different ways.
So if you have a hundred kinds of animals, and some of them can only fly, some of them can only dig and some can do both, you have both fly and digHole as methods on the superclass.
It's not about composing all of the behaviour into the superclass, though - if only dogs can dig, and it doesn't even make sense for animals in general, then it doesn't make sense for you to put digHole into Animal - when you want a dog to dig, you probably should know whether or not it is a Dog anyway, or if you want to move from Animal to Dog (for instance to get all of the dogs out of an Animal list) so that you can use the digHole method, you can use an explicit cast
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.