Static method with object as parameter

Asked

Viewed 672 times

1

I am creating a very simple system for enrolling students. I took a class Aluno as follows:

public class Aluno {
    private String nome;
    private String matricula;
    private String curso;
    private int periodo;
    private String[] disciplinasMatriculadas;
    private int idade;
    private String endereco;

    public Aluno(String nome, String matricula, String curso, int periodo,
            int quantidadeDisciplinasPermitidas) {
        super();
        this.nome = nome;
        this.matricula = matricula;
        this.curso = curso;
        this.periodo = periodo;
        disciplinasMatriculadas = new String[quantidadeDisciplinasPermitidas];
    }

    public String getNome() {
        return nome;
    }

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

    public String getMatricula() {
        return matricula;
    }

    public void setMatricula(String matricula) {
        this.matricula = matricula;
    }

    public String getCurso() {
        return curso;
    }

    public void setCurso(String curso) {
        this.curso = curso;
    }

    public int getPeriodo() {
        return periodo;
    }

    public void setPeriodo(int periodo) {
        this.periodo = periodo;
    }


    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    int d = 0;
    public String fazMatricula(String disciplina){
        if(d == disciplinasMatriculadas.length - 1){
            return "Quantidade de disciplinas excedida. O limite de matriculas para esse aluno é de " +
        disciplinasMatriculadas.length + " disciplina(s). Se desejar, cancele sua matricula em uma das disciplinas" +
                    " e faça uma nova matricula.";
        } else if(disciplinasMatriculadas.length == 0){
            return "Este aluno não pode ser matriculado em nenhuma disciplina. Por favor, fale com a secretaria.";
        } else{
            disciplinasMatriculadas[d] = disciplina;
            d++;
            return "Matricula na disciplina \"" + disciplina + "\" realizada com sucesso!";
        }
    }

    public String cancelaMatricula(String disciplina){
        boolean disciplinaMatriculada = false;
        int j = 0;
        for(int i = 0; i < disciplinasMatriculadas.length - 1; i++){
            if(disciplinasMatriculadas[i].equals(disciplina)){
                disciplinaMatriculada = true;
                continue;
            }else if(i == disciplinasMatriculadas.length - 1 && disciplinaMatriculada == false){
                System.out.println("Aluno não está matriculado na disciplina \"" + disciplina + 
                        "\", portanto não é possivel cancelar essa matricula"); 
                break;
            }else{
                disciplinasMatriculadas[j] = disciplinasMatriculadas[i];
                j++;
            }
        }return "Cancelamento da matricula na disciplina \"" + disciplina + "\" realizado com sucesso!";
    }

    public String imprime(){
        return "-----------------------------------------------------\nNome do aluno: " + nome + "\nMatricula: " +
    matricula + "\nCurso: " + curso + "\nPeriodo: " + periodo + "\nDisciplinas Matriculadas: " + 
                disciplinasMatriculadas.toString() + "\n-----------------------------------------------------\n";
    }

Then, I made a main method called Academic System that should serve for the user to choose an option and perform the desired operation.

import java.util.Scanner;

public class SistemaAcademico {

    public static void main(String[] args) {
        Aluno alunos[];

        Scanner s = new Scanner(System.in);
        System.out.println("Informe a quantidade de alunos que será cadastrada:");
        alunos = new Aluno[s.nextInt()];
        System.out.println("Digite o número da opção escolhida:");
        System.out.println("1 - Cadastrar aluno;");
        System.out.println("2 - Excluir aluno por nome;");
        System.out.println("3 - Listar alunos;");
        System.out.println("4 - Matricular aluno em disciplina;");
        System.out.println("5 - Cancelar disciplina;");
        System.out.println("6 - Imprimir lista de alunos e disciplinas matriculadas");


    }

}

I must associate each of the options with some methods, but I stalled on the first because I did not understand the signature I was asked to.

public static void cadastrarAluno(Aluno aluno){}

The Student object passed as a parameter left me confused, I do not know how to use it. In my opinion, I should have a method without parameters, instantiating an object aluno at the beginning and ask the user through prints on the screen to enter the value of each attribute of my object.

I do not know if I left my doubt clear, but as it is the user who will decide to execute the method, I do not know how this parameter will be passed.

  • The question is not at all clear. The relevant information on how the cadastrarAluno is not in it. It is unclear why this method has this signature. If you do not want to pass a parameter, do not. You may not understand what a parameter is. It is a local variable whose initialization occurs at the time of the method call. This is the question?

  • I am studying java and this is an exercise that was passed to me. In the statement I am asked to implement a method with this signature. But if the method will be called by the user at runtime, I don’t know how to assign this parameter. I know how to solve the problem without the parameter, but I kept thinking that if it was asked this way, there must be a way to do that I don’t know by knowing little.

1 answer

1


The requirement of exercise seems to make little or no sense. If the method should register the student, he should do the whole, he should not require that an object be passed to him. I would rather not use this signature and just return the created object within this method (if necessary). I’d go the way you’re thinking and justify the decision. If the teacher wants to test his ability to initialize the object outside the method, let him do a better written exercise. I hope at least it’s just another bad Internet course and nothing official.

If you insist on this, you can create an empty object (in possibly invalid state), or create with fictitious data (which I find much worse).

A way:

Aluno aluno = null;
cadastrarAluno(aluno);

Then meets the signature requirement. Within the method you will have to create the object in the received parameter

If you want to create the object before calling without the method being forced to initialize the variable (something worse) you can do so:

Aluno aluno = new Aluno();
cadastrarAluno(aluno);

But in this case you would need to have a constructor with no parameters in the class, which is not happening now. Maybe you have a requirement preventing this. I think it’s bad that you have this constructor because it allows you to have an invalid object and would even have difficulty identifying that this is happening. The null at least makes clear the invalidity of the state.

The last option would be:

Aluno aluno = new Aluno(null, null, null, 0, 0);
cadastrarAluno(aluno);

Obviously the student parameter in the method already works as a local variable declared in the method. Your initialization will occur in the method call, so you do not need to create a variable to manipulate this object, this variable is already the parameter.

Try to understand what is the variable and what value is. Contrary to popular belief among programming beginners, they are distinct things. An argument passage to a parameter is to pass a value, the parameter is the variable.

The operator new is used to create an object, i.e., create a value by reference.

The signature would be better:

public static Aluno cadastrarAluno()

I put in the Github for future reference.

Browser other questions tagged

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