Only one class can instantiate another class, how do we do that?

Asked

Viewed 169 times

3

Hi, I’m doing an UML on an exercise, but I can’t do a part of it.

The exercise says that only the administrator class can create another contributor, I wanted to know how I could implement this.

inserir a descrição da imagem aqui

Example of what I have done so far below:

STAFF CLASS

package com.trabalho1;

public abstract class Funcionario {

    protected String nome;
    protected String cpf;

    public Funcionario(String nome, String cpf){
        this.nome = nome;
        this.cpf = cpf;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

}

ADMINISTRATOR CLASS

package com.trabalho1;

public class Administrador extends Funcionario{

    public Administrador(String nome, String cpf) {
        super(nome, cpf);
    }
}

CLASS COLLABORATOR

package com.trabalho1;

public abstract class Colaborador extends Funcionario{

    public Colaborador(String nome, String cpf) {
        super(nome, cpf);
    }

}

COURIER CLASS

package com.trabalho1;

public class Entregador extends Colaborador{

    public Entregador(String nome, String cpf) {
        super(nome, cpf);
    }

}

2 answers

1


If only one Administrador can create a Colaborador, that means that no one else can create it, that is, its builders cannot be public. Remove the public of the builders of Colaborador and their subclasses:

public abstract class Colaborador extends Funcionario {
    // construtor sem "public"
    Colaborador(String nome, String cpf) {
        super(nome, cpf);
    }
}

public class Entregador extends Colaborador {
    // construtor sem "public"
    Entregador(String nome, String cpf) {
        super(nome, cpf);
    }
}

Leaving so, only classes within the same package "see" the constructors. And as the Administrador is the only one who can create these classes and it is in the same package (com.trabalho1), that’s exactly what we need.

Therefore, the only point at which a Colaborador can be created is within classes that are in the same package - and Administrador is one of them. And if only the Administrador can create these classes, then you create a public method in this class, which will be responsible for creating collaborators.

Moreover, Colaborador is an abstract class, and it is not possible to instantiate it. We can only instantiate its subclasses. So one way to do it would be to have a method that received the type of employee to be instantiated, in addition to the information needed to build it (in this case, the name and CPF).

In the example below I am using a int as the type of collaborator, but in these cases I prefer to use a enum (like I don’t know if you ever know enum, I’ll leave the example with int first):

public class Administrador extends Funcionario {
    public Colaborador criaColaborador(int tipo, String nomeColaborador, String cpfColaborador) {
        if (tipo == 1) {
            return new Entregador(nomeColaborador, cpfColaborador);
        } else if (tipo == 2) {
            // retorna outro tipo de colaborador (Secretaria, Gerente, etc)
        }
        // vários if's, para cada tipo de colaborador

        // tipo desconhecido, retorna null (ou algum valor default)? lança exception? você decide
        return null;
    }
}

In case you already know enum, gets like this:

public enum TipoColaborador {
    SECRETARIA, GERENTE_VENDA, ENTREGADOR;
}

public class Administrador extends Funcionario {
    public Colaborador criaColaborador(TipoColaborador tipo, String nomeColaborador, String cpfColaborador) {
        if (tipo == TipoColaborador.ENTREGADOR) {
            return new Entregador(nomeColaborador, cpfColaborador);
        } else if (tipo == TipoColaborador.GERENTE_VENDA) {
            // retorna outro tipo de colaborador (Secretaria, Gerente, etc)
        }
        // vários if's, para cada tipo de colaborador

        // retorna null (ou algum valor default)? lança exception? você decide
        return null;
    }
}

I’d rather use enum because it makes it clear which values can be passed on the type. If I use int, I can unintentionally pass some number that has nothing to do with the guy, for example.

Remembering that this is just one way of doing. It is also possible to have a method for each type (criarEntregador, criarSecretaria, etc), use Map to map types and their classes (Map<TipoColaborador, Class<? extends Colaborador>>), among others (in addition to the obvious "use switch instead of if", if you already know).

But the general idea for your problem is this. By not letting the class have public constructors, you limit and control who can create instances of it. In this case, the only place in which these builders are called is in the public method that is in Administrador, which means that only this class can create instances of Colaborador.

To create your instances, would look like this:

Administrador admin = new Administrador("Admin", "12345678909");
Colaborador col = admin.criaColaborador(TipoColaborador.ENTREGADOR, "Fulano de Tal", "11122233396");
  • :), worked, but as I am still layman in java came another problem. How to reference this object I just created in memory? For I will use it in other classes.

  • @Wesleybelizario I edited the answer, added an example at the end

1

When you go to implement the employee registration (if you want to implement this restriction in the functionality), you in the class that performs the registration will check if the Employee who is logged in to the system is of the type Administrator! If it meets the condition you save the contributor, otherwise you throw an exception stating that the user is not allowed to perform this action on the system.

The other way to solve this problem is by showing the option in the menu for the employee registration if it is of the Administrator type (you will have to do this check in the system login), before showing the screen with the options. So when they log in you will know what options are available to this employee.

  • 1

    This is an exercise, and in this case, I would have to use abstract classes, inheritance or whatever. As this is a basic POO exercise I wanted to find a simple way to this problem.

  • Inheritance as well as composition are one of the pillars of object orientation, so to perform the exercise in the right way you necessarily need to use the concepts of the paradigm.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.