I am trying model a zoo.
Suppose I have the following structure for areas in the Zoo(omitted some details)
public abstract class AnimalHabitat{
private ArrayList<Animal> animals = new ArrayList<>();
public void setAnimal(Animal animal) {
animals.add(animal)
}
}
public class Enclosure extends AnimalHabitat{}
public class Aquarium extends AnimalHabitat{}
public class Cage extends AnimalHabitat{}
Then I have the following structure for animals
public abstract class Animal{}
public class Lion extends Animal{}
public class Zebra extends Animal{}
public class Shark extends Animal{}
public class Starfish extends Animal{}
public class Parrot extends Animal{}
public class Eagle extends Animal{}
I want to add an animal to its corresponding appropriate habitat. To simplify code I was thinking to use either a marker interface, such as
public interface TerrestrialAnimal{}
public class Lion extends Animal implements TerrestrialAnimal{}
public class Zebra extends Animal implements TerrestrialAnimal{}
and then I will be able to do
public class Zoo{
public boolean addAnimal(AnimalHabitat habitat, Animal animal) {
if (animal instanceOf TerrestrialAnimal && habitat instanceOf Enclosure) {
habitat.set(animal);
return true;
}
if (animal instanceOf AquaticAnimal && habitat instance of Aquarium) {
habitat.set(animal);
return true;
}
// So for aerial
}
}
However an alternative is to use enums. For example suppose I have
public enum AnimalType{
Terrestrial, Aquatic, Aerial;
//getter
}
Then in the Animal abstract class I can define
public abstract class Animal{
private AnimalType type;
// Initialise in the constructor depending on the animal instance
}
And I will do the same in the addAnimal() method in Zoo.
What are the pros and cons of each approach? Thanks!
I would use enums. You don't need all of those if statements.
Just have the attribute type in both Animal and AnimalHabitat and then compare them.
if (animal.getType() == habital.getType()) { // can add to habitat
Switch to interfaces if you want to add some methods to the interface specific to the animal type.
Enum
pros:
Easy to scale: You can easily add value
More coincise: You have one single file to define all AnimalType
More readable: definitely readable
More Flexible: You can define method on Enum and you can print AnimalType using enum value
Comparable: You can do simple compare instead of using instanceof
with enums approach i doesn't find any cons.
Interface
pros
Methods: You can define common methods signatures
You can use 2 interfaces in same Animal (may an animal have more habitat? Or more types?)
you can use interface as supertype in collections/class variable
cons
Expensive: definitely expensive, one interface for each type
In your example i prefer Enums because you are using interfaces to define animal types and it can be done easily using Enums. Use interfaces if you need to define common method signatures or you want to use Interfaces as supertype as follow:
List<TerrestrialAnimal> terrestrialAnimal = new ArrayList<>(); it can contains all terrestiral animal.
Related
Can somebody explain (like for dummies) the following examples of inheritance in Java:
1) public class Dog <T extends Animal> {....
2) public class Buldog extends Dog<DogFood, DogCommands> {....
3) public class Buldog<T extends DogFood, K extends DogCommands> extends Animal implements LivingBeign, LivingThing<T,K> { ....
1) public class Dog <T extends Animal> {...
There will be an generic type In your Dog class which is inherit variables and methods from class (probably an abstract class Animal)
This T must have and animal property.. For example assume you have a class Mammalian. We know that all mammalian are animal so they have what all animals have, and they can what all animals can.
So yo can call this as
public Dog<Mammalian> myDog = ...
There is a different situation.
2) public class Buldog extends Dog<DogFood, DogCommands> {....
So your dog class should be written like
/** T refers the food, and K refers commands*/
public class Dog<T,K> {....
So when you want to extend your class with Bulldog, you can leave generic or specify those generic types..
3) public class Buldog<T extends DogFood, K extends DogCommands> extends Animal implements LivingBeign, LivingThing<T,K> { ....
This is also as easy as above codes. The difference that you are desiring subclass of DogFood, which can be anyting, it can be Pap or Milk or Meat, and some subclass of DogCommands for example SitCommand, PlayCommand.. And as you are creating Buldog you know that It is Animal, so you don't want to write animal's property and methods again and since in Java you can't multiple inherit, you want also the other interfaces methods in your class..
I hope it is more understandable now.
I have the abstract parent class Animal:
public abstract class Animal
{
public abstract <T extends Animal> T copyAnimal(T animal);
}
I then want to create a subclass Duck but to override the copyAnimal I want to use Duck as the parameters such that:
public class Duck extends Animal
{
#Override
public Duck copyAnimal(Duck duck)
{
return copyOfDuck;
}
}
This of course gives me a compiler error saying that the method is not overridden. That being said how can I adjust this code so that I don't have to pass Animal to the copyAnimal() method to save casting, etc. since it looks ugly and would require additional runtime checks. Or is it even possible? And if not then what's the most elegant solution?
public abstract class Animal<A extends Animal<A>>
{
public abstract A copyAnimal(A animal);
}
Then:
public class Duck extends Animal<Duck>
Note that you can't constrain it to be the "self" type (e.g. it could be Duck extends Animal<Pig>); you just have to only declare the classes you want to declare.
For instance, I have an abstract class implemented like this:
public abstract class Animal
{
public abstract void makeNoise();
}
and I have a child class which is representing an animal that does not make any noise. Which is better?
public class Turtle extends Animal
{
// properties and methods
public void makeNoise()
{
//leave it empty
}
}
or should i simply make it : public abstract void makeNoise(); inside Turtle?
It is better to move the makeNoise() method out of Animal as all the animals doesnot make noise. So create another interface NoiseMaker and add the the makeNoise method inside that.
public abstract class Animal {
// animals methods
}
public interface NoiseMaker {
void makeNoise();
}
public class Turtle extends Animal {
// properties and methods which are applicable for turtle
}
And when you want an animal which makes noise like Lion you can extend Animal class and implement NoiseMaker, so that it has the behaviour of Animal as well as it makes noise.
public class Lion extends Animal implements NoiseMaker {
public void makeNoise() {
// implementation
}
// other properties and methods which are applicable for turtle
}
What people often do: throw some sort of exception, like UnsupportedOperationException or something alike.
But: in the end your are fixing a symptom here.
The point is: extending a base class means that an object of the derived class IS-A object of the base class as well. And you are asking: how to violate the public contract of the base class.
And the answer is: you should not do that. Plain and simple.
Because if you start throwing exceptions here, all of a sudden, a caller that maybe has List<Animal> animals can't simply invoke makeNoise() on each object. The caller has instead to use instanceof (so that he can avoid calling makeNoise() on specific classes) - or try/catch is required.
So the real answer is: step back and improve your model. Make sure that all methods on the base class make sense for derived classes. If not - maybe introduce another layer, like abstract class NoisyAnimal extends Animal.
This is the best use case to use UnsupportedOperationException
You have to implement because of the abstract design. So just implement the method and throw UnsupportedOperationException exception.
Keep it Animal, cause most of the Animal's make sound :) If you move it to Turtle, all the subclasses again have to have their own voice method.
or should i simply make it : public abstract void makeNoise(); inside Turtle?
If you do, Turtle is abstract. So the question isn't which is better, the question is, do you want to be able to instantiate Turtle or not?
If you do, you have to implement the method.
If you are okay with it being abstract, then declare it abstract and don't list the method at all:
public abstract class Turtle extends Animal {
}
You might want to distinguish between Animals making noises or not. Something a long the lines of
public abstract class Animals {}
public abstract class AnimalsNoisy extends Animals { abstract void makeNoise(); }
You would then use Turtle extends Animals. The advantage of this structure is if you have a List of Animals you don't need to worry if they implemented the makeNoise method or not e.g.
for(AnimalsNoisy animal: ListAnimalsNoisy) { animal.makeNoise();}
It is a good example to learn how to make your code loosely coupled.
By loosely coupled I mean, if you decide to change or modify your code you will not touch your previous code. Sometimes it is referred as OPEN-CLOSE principle.
For this first you have to identify what part of your code is frequently changing.
Here the method makingNoise() will have different implementation based on your class.
This design can be achieved in following steps.
1) Make an interface which will have implementation for makeNoise()
method.
public interface NoiseInterface {
public void speak();
}
2) Create concrete implementation for NoiseInterface
eg: For Fox
public class FoxSound implements NoiseInterface {
#Override
public void speak()
{
//What does the fox say ?
Sysout("chin chin chin tin tin tin");
}
}
3: Provide the Noise Interface in Animal Class
public abstract class Animal
{
public NoiseInterface noiseMaker;
public abstract void makeNoise();
}
4: Just provide the Type of NoiseInterface of your choice in Fox Class
public class Fox extends Animal
{
public Fox()
{
noiseMaker = new FoxSound();
}
public void makeNoise()
{
noiseMaker.speak();
}
}
Now Amazing thing about this design is you will never have to worry about the implemetation. I will explain you how.
You will just call
Animal me = new Fox();
fox.makeNoise();
Now in future you want to mute the Fox.
You will create a new Interface Mute
public class Mute implements NoiseInterface {
#Override
public void speak()
{
Sysout("No sound");
}
}
Just change the NoiseBehavior in Fox class constructor
noiseMaker = new Mute();
You can find more on OPEN-CLOSE Principle Here
You may write like this,is this what you want?
public interface NoiseInterface {
void makingNoise();
void makingNoNoise();
}
public class Animal implements NoiseInterface{
#Override
public void makingNoise() {
System.out.println("noising");
}
#Override
public void makingNoNoise() {
System.out.println("slient");
}
}
public class Turtle extends Animal{
#Override
public void makingNoNoise() {
System.out.println("turtle");
super.makingNoNoise();
}
}
Let's say that I have an interface, and all classes that implement that interface also extend a certain super class.
public class SuperClass {
public void someMethod() {...}
}
public interface MyInterface {
void someOtherMethod();
}
//many (but not all) sub classes do this
public class SubClass extends SuperClass implements MyInterface {
#Override
public void someOtherMethod() {...}
}
Then if I'm dealing with an object of type MyInterface and I don't know the specific sub class, I have to hold two references to the same object:
MyInterface someObject = ...;
SuperClass someObjectCopy = (SuperClass) someObject; //will never throw ClassCastException
someObjectCopy.someMethod();
someObject.someOtherMethod();
I tried making the interface extend the super class, but it's a compiler error:
public interface MyInterface extends SuperClass {} //compiler error
I also thought of combining the interface and the super class into an abstract class like so:
public abstract class NewSuperClass {
public void someMethod();
public abstract void someOtherMethod();
}
But then i can't have a sub class that doesn't want to implement someOtherMethod().
So is there a way to signify that every class that implements an interface also extends a certain class, or do I have no choice but to carry around two references to the same object?
I think that the only solution you have would be to have a reference to both, but this indicates that you have a design flaw somewhere. The reason I say is because you should think of an interface as something that your implementing classes will always need. For example, a Car and Airplane both need a Drive() interface. A design reconsideration is probably worth your time. However, if you still want to follow that path, you can do the following:
public class ClassA {
public void methodA(){};
}
public abstract class ClassB extends Class A{
public void methodB();
}
After you have the above setup, you can now reference an object that has the two methods by doing the following:
ClassB classB = new ClassB();
classB.methodA();
classB.methodB();
Now you don't actually have to actually use two pointers to the same object.
I have a question like this :
Think a scenario like this
public class Animal {
protected String Name;
Boolean canWork;
}
public class Dog {
Enum TailType
}
And I need to have both of this classes attributes in a class of the third level which extends the both classes .. but using interfaces I don't think this can be achieved. Is it possible to do this using a design pattern or some else method ?
Summary : I want to have attributes from two classes to a concrete class
You can have Dog extend Animal, then extend Dog by the third class, but unless your 3rd class is Poodle then you may have a problem you don't realize yet. That being inheritance is only appropriate when the relationship is a modeling criteria, and extending objects only to get their functionality is the wrong approach. Inheritance should follow the IS-A principle. That being your subclass IS-A base class in modeling terms. If it doesn't pass that test you are using inheritance when you shouldn't. After all you can use delegation to obtain their functionality. That meaning:
public class SomeClass {
private Dog dog;
public void bark() {
dog.bark(); // this is reusing the functionality without extending
}
}
Now SomeClass can call or invoke methods on Dog without extending it. Now the downside to this is a reference to Dog can't point to SomeClass, but if SomeClass is-not-a Dog that's probably good. However, if you have to allow Dog and SomeClass to share some typing so you can have a reference that points at either Dog or SomeClass then you can create an interface that both share:
public class SomeClass implements Barkable {
private Dog dog;
#Override
public void bark() {
dog.bark();
}
}
public class Dog implements Barkable {
#Override
public void bark() {
System.out.println( "Bark! Bark!" );
}
}
With delegation/composition and interfaces you DON'T need multiple inheritance. It's a really simple technique to apply and master and you'll build systems that are much more flexible than relying on inheritance alone.
if you are trying to have just attributes, I think you can use interfaces like:
interface A{
int a = 0;
}
interface B{
int b = 1;
}
class implements A, B{
//can access A.a and B.b
}
But this is not a good approach, interfaces are meant for contracts not just to contain constants (variables in interface are static and final by default)
For good reasons modern OO languages like Java and C# do not support multiple inheritance.
The replacement to use in most cases is the interface:
public Interface NameAndWorkable {
setName(String name)
String getName();
boolean canWork();
setCanWork(boolean canWork);
}
public Interface TailAnimal {
TailtypeEnum getTailType();
setTailType(TailtypeEnum tailtype);
}
public class Animal implements NameAndWorkable {
private String name;
private boolean canWork;
public setName(String name)
public String getName();
public boolean canWork();
public setCanWork(boolean canWork);
}
public class Dog implements TailAnimal {
private TailTypeEnum tailType;
public TailtypeEnum getTailType();
public setTailType(TailtypeEnum tailtype);
}
and now the third object with fullfills both Interfaces
public class WorkingNamedDog implements NameAndWorkable, TailAnimal {
private String name;
private boolean canWork;
private TailTypeEnum tailType;
// from NameAndWorkable
public setName(String name)
public String getName();
public boolean canWork();
public setCanWork(boolean canWork);
// from TailAnimal
public TailtypeEnum getTailType();
public setTailType(TailtypeEnum tailtype);
}
To achieve multiple inheritance, it is necessary to use Interfaces. You can either use inheritance by extending these classes on one another like:
//Your first class
public abstract class Animal{
//It is upto you to use an abstract method inside it. However it is not necessary to do so!
//define an abstract method inside an abstract class.
}
//Your second class
public class Dog extends Animal{
}
//Your third class
public class ThirdClass extends Dog{
//here you can instantiate Dog
private Dog dogObject = new Dog();
public void anyMethod(){
dogObject.anyMethodsThatAreDefinedInClassDogAndAnimal();
}
}
Hope this helps!!
You can extend one class and have another class as composition like this:
public class MyClass extends Dog {
private Animal animal; // instance of Animal class
// rest of the code to expose Animal class's attributes as per your need
}
Dog should be a subclass of Animal. Then your third class would be a subclass of Dog. This third class would have the attributes of Dog and Animal.
If Dog is not a subclass of Animal then you would need multiple inheritance to achieve what you want. Since Java does not support multiple inheritance you have to make Dog a subclass of Animal.
Or in case, your two classes are not in same inheritance hierarchy, then you have two options: -
Either make them interfaces, and then you can implement both the interfaces.
Or, use Composition instead of Inheritance, in which case, you would need to have the references to both the classes - Animal and Dog, as attribute in your class.
E.g: -
public class YourClass {
Animal animal;
Dog dog;
}
However, it doesn't make sense to have Animal and Dog class, with Dog not being a subclass of Animal. So, you should change that first, and then you would be able to use inheritance.