Java - Using Accessor and Mutator methods

前端 未结 2 1617
抹茶落季
抹茶落季 2020-11-27 05:34

I am working on a homework assignment. I am confused on how it should be done.

The question is:

Create a class called IDCard that contains a

2条回答
  •  旧时难觅i
    2020-11-27 06:13

    You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

    public class IDCard {
        public String name, fileName;
        public int id;
    
        public IDCard(final String name, final String fileName, final int id) {
            this.name = name;
            this.fileName = fileName
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    }
    

    You can the create an IDCard and use the accessor like this:

    final IDCard card = new IDCard();
    card.getName();
    

    Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

    If you use the static keyword then those variables are common across every instance of IDCard.

    A couple of things to bear in mind:

    1. don't add useless comments - they add code clutter and nothing else.
    2. conform to naming conventions, use lower case of variable names - name not Name.

提交回复
热议问题