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;
}
}
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:
name
not Name
.Source: Stackoverflow.com