Does anyone know if it is possible to create a table for an abstract class in ActiveAndroid. For example i could have an abstract class Animal with two concrete classes Dog and Cat. I want to be able to do something like:
List<Animal> animals = new Select().from(Animals.class).execute();
which would result in 'animals' containing all of the saved Cats and Dogs.
Or:
Animal animal = new Select().from(Animals.class).where("name = ?", name).executeSingle();
Where 'animal' could be either a Cat or a Dog.
Unfortunately when I do this I get an exception because no table is created for the abstract class Animal.
Does anyone know how I might go about this using ActiveAndroid?
Unfortunately ActiveAndroid does not support inheritance of models in that way just yet (https://github.com/pardom/ActiveAndroid/issues/14, https://github.com/pardom/ActiveAndroid/issues/257).
If you wanted to modify ActiveAndroid here's what you could do:
Create some kind of annotation that allows you define a model (Animals) as something that isn't persisted (refer to com.activeandroid.annotation.Table).
Upon trying to executing queries for that class you could use reflection to determine its child classes and then have it perform that query per child class.
Then you would basically take the list of results for each query and combine them into a single list and return that.
To be honest I've never seen inheritance in any Android ORM libraries, and personally I don't think it's a good design pattern for models. You may want to reconsider your reasoning for going down this path.
Related
Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.
Say I have:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
Should I use:
public class Person{
ICar car;
.
.
public Person (ICar c){
car = c;
}
}
or
public class Person<T extends ICar>{
T car;
.
.
public Person(T c){
car = c;
}
}
or does it depend on the tasks performed?
Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?
A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.
Think about what you try to mimic from the real world, before going into such programming details.
The distinction isn't always clearcut but here are a few clues:
Try to think of them as "type parameters" (Which they are.) They are associated with the class but they're not necessarily related to it. (Look at the collections framework for example.)
Type parameters can only be used if they don't change throughout an object's lifetime. This sounds quite obvious, but it's a very handy rule to decide when NOT to use generics. (Example is a person who can change cars.)
On the other hand, if not many instances will use the type parameter, if it's too optional, that's not a good idea either. (A lot of people might not have cars at all.)
And finally, a general thought that I found really useful: if you're unsure, don't be afraid to prototype it. Write the code both ways and check which one looks simpler and easier to comprehend. Show it to someone else without any explanations or maybe wait a day or two and then re-read the code yourself. Then throw the other one away. Throwing away code is good.
You need the generics version if you have any methods that take or return anything involving a T, or if it's possible for other people to access your car field. (Since you didn't show any methods, we can't really tell.)
For example, with the generics version you can have a method like T someMethod();, then when someone has a Person<Honda>, they know they can get a Honda back when they call someMethod, rather than some unknown type of car if you didn't have generics.
Similarly, with the generics version you can have a method like void anotherMethod(T anotherCar);, then when someone has a Person<Honda>, this forces them to pass a Honda to this method, instead of any car.
So basically, having a generic class allows you to place constraints on uses of the object later on (method calls etc.). If the constructor is the only place that you use T, and you don't need to use T in any methods or fields, then yes, there is no point for it.
This has to do with using Inheritance versus Composition.
Without knowing any other semantics, Composition seems more relevant. A person may change cars, without becoming a different person.
http://www.artima.com/objectsandjava/webuscript/CompoInherit1.html
http://en.wikipedia.org/wiki/Composition_over_inheritance
I'd tend to favor composition (what you're calling dynamic binding), especially in the case you use. A person is not a type of ICar, so using the generics here is kind of weird (to me anyway). I'd use generics as a way of saying "A container for ICar", as in Garage although in that case I might just use a collection type as a variable, or extend the collection type if really needed.
I'd suggest to focus on semantics first:
Providing that you may have a Bmw and a Toyota classes implementing the ICar interface, then make this question: can a Person change his car or would it be a different person if he does so?
The generics approach will force you to create a new Person instance if for some reason you need to change the value of the car attribute from Toyota to Bmw in an existent person instance and thus, this new person will be different from the previous one. Of course, you could create the first Person instance as Person<ICar> instead of hooking it to a specific car class but, why use generics then?
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.
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!
I was going through a Java code and I saw that objects have been allocated using some interface and this interface contains some methods to allocate objects using new operator. I am unable to think that why they have used an interface instead of just directly allocating objects using new operator. e.g:
Animal animal = new Animal();
OR
Animal animal = interface.allocateAnimal()
here interface is an interface having a method allocateAnimal which does nothing but
new Animal().
So ultimately we are doing same thing but in different way so what are gaining here?
EDIT 1: Actually interface is implemented somewhere else. So interface does not contain any implementation code, it just contains methods.
First of all interfaces are not allocating anything. They are just establishing contracts.
What you see there is the factory method pattern. Someone decided to implement that interface and the concrete implementation's method is creating an Animal object. You can check the link to the pattern and there you'll find a thorough explanation about the factory method.
There is a question here about the reasons using the factory pattern it might worth checking out. Here is the point:
...using a Factory allows the consumer to create new
objects without having to know the details of how they're created, or
what their dependencies are - they only have to give the information
they actually want.
There is something more: the person who have written the code you are reading may be tried to refer to the programming interface of something which is not the technical interface keyword in java. It means something else.
It's a design pattern called Factory Method.
Note: while a class has an API (application programming interface), "interface" on it's own has a special meaning/ is a key word in Java. As your example has an implementation of the method it cannot be an interface.
Edit
If it's really a Java interface, then you might see an implementation of the Abstract Factory design pattern:
http://en.wikipedia.org/wiki/Abstract_factory_pattern
I don't think there is actually any code in the interface, since an interface cannot have implementation.
However, the reason why you would like to use an interface.allocateAnimal(), is that sometimes you don't know which animal you want to get a new from.
It could be a horse, dog, cat etc.
Only in runtime do you know. So the interface object will in runtime be an implementation, for instance Cat, and the Cat object will have a new Cat() which it will return.
Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.
Say I have:
public class Honda implements ICar(){
}
public class Opel implements ICar(){
}
Should I use:
public class Person{
ICar car;
.
.
public Person (ICar c){
car = c;
}
}
or
public class Person<T extends ICar>{
T car;
.
.
public Person(T c){
car = c;
}
}
or does it depend on the tasks performed?
Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?
A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.
Think about what you try to mimic from the real world, before going into such programming details.
The distinction isn't always clearcut but here are a few clues:
Try to think of them as "type parameters" (Which they are.) They are associated with the class but they're not necessarily related to it. (Look at the collections framework for example.)
Type parameters can only be used if they don't change throughout an object's lifetime. This sounds quite obvious, but it's a very handy rule to decide when NOT to use generics. (Example is a person who can change cars.)
On the other hand, if not many instances will use the type parameter, if it's too optional, that's not a good idea either. (A lot of people might not have cars at all.)
And finally, a general thought that I found really useful: if you're unsure, don't be afraid to prototype it. Write the code both ways and check which one looks simpler and easier to comprehend. Show it to someone else without any explanations or maybe wait a day or two and then re-read the code yourself. Then throw the other one away. Throwing away code is good.
You need the generics version if you have any methods that take or return anything involving a T, or if it's possible for other people to access your car field. (Since you didn't show any methods, we can't really tell.)
For example, with the generics version you can have a method like T someMethod();, then when someone has a Person<Honda>, they know they can get a Honda back when they call someMethod, rather than some unknown type of car if you didn't have generics.
Similarly, with the generics version you can have a method like void anotherMethod(T anotherCar);, then when someone has a Person<Honda>, this forces them to pass a Honda to this method, instead of any car.
So basically, having a generic class allows you to place constraints on uses of the object later on (method calls etc.). If the constructor is the only place that you use T, and you don't need to use T in any methods or fields, then yes, there is no point for it.
This has to do with using Inheritance versus Composition.
Without knowing any other semantics, Composition seems more relevant. A person may change cars, without becoming a different person.
http://www.artima.com/objectsandjava/webuscript/CompoInherit1.html
http://en.wikipedia.org/wiki/Composition_over_inheritance
I'd tend to favor composition (what you're calling dynamic binding), especially in the case you use. A person is not a type of ICar, so using the generics here is kind of weird (to me anyway). I'd use generics as a way of saying "A container for ICar", as in Garage although in that case I might just use a collection type as a variable, or extend the collection type if really needed.
I'd suggest to focus on semantics first:
Providing that you may have a Bmw and a Toyota classes implementing the ICar interface, then make this question: can a Person change his car or would it be a different person if he does so?
The generics approach will force you to create a new Person instance if for some reason you need to change the value of the car attribute from Toyota to Bmw in an existent person instance and thus, this new person will be different from the previous one. Of course, you could create the first Person instance as Person<ICar> instead of hooking it to a specific car class but, why use generics then?