Use set with Scanner and array

1

I have the following question: I'm using the following code that works quietly

System.out.println("Digite a Primeira Nota: ");

Scanner inNota1 = new Scanner(System.in);

 estud.notas[0] = inNota1.nextDouble();

But when learning about the private and set method I do not know how to build the code. Would it look something like this ??

System.out.println("Digite a Primeira Nota: ");
        Scanner inNota1 = new Scanner(System.in);
        estud.setNotas[0](inNota1.nextDouble());

As I have specified, when I use public method I can use the first code with the Scanner quietly, now using the private method, I do not know how to assign the position of the array's memory and how to insert the Scanner variable in the set syntax

    
asked by anonymous 04.09.2017 / 21:20

1 answer

1

private and set are different concepts:

private

The keyword private is what we call Access Modifier . There are basically three access modifiers: public , protected and private :

  • public : This is the most "open" access modifier in Java. Any class can access the member that owns this access modifier. It does not have to be a child class of the class that has members with this access modifier (also known as public members ) nor be in the same package;

  • protected : This access modifier restricts access to the member in which it is used so that it is accessed only by the classes that inherit from the class that has the members with that access modifier and the classes that are in the same package;

  • private : This access modifier is the most "restricted" Java modifier. It restricts access of members who have this modifier access only to the class itself and classes that are in the same package;

set

The term set ( in this case ) refers to methods setters .

In Java there is the encapsulation concept, which says (in a simple way) that its attributes must be accessed by methods only if they are accessed outside the class itself.

For example:

public class Pessoa {

    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) { //método "setter"
        this.nome = nome;
    }
}

What you (probably) are trying to do is a private method:

private void setNota(double nota) {
    estud.notas[0] = nota;
}

Considering the two topics (the private access modifier and the setter method), it's up to you to decide if you really want to do this. I particularly find it silly to access a member of its own class through a setter method.

If you were to "set" the value of estud.notas[0] through another class, then it would be advantage / correct to use a setter for this and would also need to check the correct access modifier for the scenario .

    
04.09.2017 / 21:47