How to call constructors with arguments?

2

How to set constructor values in the main class by Scanner in a constructor like this?.

public Aluno(String nome,int idade) {
 this.nome = nome;
this.idade = idade;
}

and in the main class call:

Aluno pedro = new aluno();

and insert the data into the main class with Scanner .

    
asked by anonymous 29.01.2016 / 20:10

1 answer

1

The code is right but could do better:

class Aluno {
    String nome;
    int idade;
    public Aluno(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }
    public Aluno() { }
}

class Principal {
    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        Aluno aluno = new Aluno();
        System.out.println("Qual tu nome");
        aluno.nome = entrada.nextLine();

        System.out.println("Qual tu idade");
        aluno.idade = entrada.nextInt();

        System.out.println("Nome: " + aluno.nome + "\nIdade: " + aluno.idade);   
    }
}

See running on ideone .

You might wonder if you should have the constructor without parameters. In actual codes, it might not be a good idea, it is not ideal to create an object in an invalid state. But in an exercise is no problem, even more than the solution that was being given was to create an object with invalid state "by force".

If you did not have the parameterized constructor, then you would not need a constructor, so when you do not have constructors, Java creates a parameterless pattern that does not initialize.

See more about builders .

    
29.01.2016 / 21:03