Search code examples
javaandroidoopbackendless

Backendless - Save object as parent class


Having the following structure (in an Android Java project):

public abstract class A {
   ...
}

public class B extends A {
   ...
}

public class C extends A {
   ...
}

At some point it is needed to store a list of parent class types cause we are using polymorphism.

But, if we try to store an object of parent type like this:

A aObject = xObject; //(xObject could be an object of type B or C)
Backendless.Persistence.save(aObject, new AsyncCallback<A>() { ...

We will get an "Cannot update object without any properties:CREATOR" error because we are trying to store an abstract class.

Is it possible to achieve this goal? The difference between child classes B and C are the way they perform some actions like rendering some image and text.

Edit 1: Specific case

The specific case is an Android app to create Memes (a Meme is a funny image with some text inside). In this case Memes can be drawn in the classic way which is an image with a text on the top and another text on the bottom. Memes can be drawn as Quote as well, which is an image with a black square at right which contains a sentence and the author below.

To model this problem I created an abstract class Meme which contains the attributes (name, topText, bottomText, image, etc...) and the methods that child classes should use to draw the image, and two child classes ClassicMeme and QuoteMeme which draw the meme in their own way.

The problem is that when a user is creating a Meme he can switch the type of Meme to draw, so I need a polymorphic reference to deal with this situation. When I proceed to store the Meme (base class) object I realize that is not possible because Meme is an abstract class, and of course I do not know what kind of child object is contained in this base class reference. (Hope I have explained clearly).


Solution

  • Your reason for having this problem is that the classes:

    perform some actions like rendering some image and text differently

    This issue / requirement has nothing to do with your data model classes so it should not be in the same class(es). The data model classes should be plain classes with only properties and effectively zero functionality.

    So, you should create some 'presenter' classes, or something like that, to own the logic related to how the data is displayed. When you need to show the data, create an instance of one of those classes and pass it an instance of a data model class. It can then get the data that it needs and display it as desired.

    In this way your data model and persistence layer are clean and effective, and you can easily add any presentation styles you want without impacting that data model.