POO in Java - Create instance in child class from parent class

0

Suppose the class ParentForm that will be used as a means to formulate the basis of the rest of the classes of an application, and suppose a class called ChildClass that will inherit from the parent class.

In ClasePadre we have a static method that performs certain operations and generates a new instance of itself and returns it. What I would like to achieve and I can not think of how to implement it is that in ChildClass, calling this method inherited from ParentClass the instance is a ChildClass object (not ParentClass).

The goal of all this is to have a class called DataModel that will serve as the basis for all the data models of my application, connect to an SQLite and collect the data. I am implementing a static method called findById that searches for a specific record in the database, maps the data into a variable and returns an instance of the class with the collected data. As an example:

public static DataModel findById(String id){
    DataModel aux = new DataModel();
    /* ... búsqueda en SQLite según el id... */
    return aux;
}

In this code we will get an exception because the admin variable is of the User type, not of the DataModel type:

class Usuario extends DataModel{
    protected String table = 'users';
}

int main(){
    Usuario admin = Usuario.findById("1");
}

Here lies the question, how to get the class to return an instance of itself? I can do this? That is, when I use the findById method in the User class, I get a Non-DataModel User instance.

A thousand thanks!

    
asked by LordVermiis 02.01.2018 в 09:37
source

1 answer

1

In Object Orientation the Inheritance is supposed to be used to define families of objects, this means that for example if you have a Base Object and an extended Object, the spread is all of the base plus some particularities. In the example you want the base class to have access to the daughter, in inheritance the accesses are generally in the other direction (to justly take advantage of the inheritance). There is a risk of circular dependence on what you mention.

Regarding the static or non-static, the static data remains unchanged regardless of the instances of objects that exist.

I advise you to read a little about inheritance and static data first. In the example you are mixing the task of looking for objects with the representation of them, and the storage. A good object-oriented system separates tasks into objects, encapsulates information and works on the basis of collaboration.

:)

    
answered by 02.01.2018 в 20:20