[java] Java - Using Accessor and Mutator methods

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 person's name, ID number, and the name of a file containing the person's photogrpah. Write accessor and mutator methods for each of these fields. Add the following two overloaded constructors to the class:

public IDCard() public IDCard(String n, int ID, String filename)

Test your program by creating different ojbects using these two constructors and printing out their values on the console using the accessor and mutator methods.

I have re-written this so far:

public class IDCard {
String Name, FileName;
int ID;

public static void main(String[] args) {

}

public IDCard()
{
    this.Name = getName();
    this.FileName = getFileName();
    this.ID = getID();
}

public IDCard(String n, int ID, String filename)
{

}

public String getName()
{
    return "Jack Smith";
}

public String getFileName()
{
    return "Jack.jpg";
}

public int getID()
{

        return 555;
    }
}

This question is related to java accessor mutators

The answer is


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.