Consider the Student class. Each student has a unique yorkID in the format of York-X, where X is the serial number, starting from 1. That is, the first Student object gets yorkID York-1, the second object gets York-2.
A) Add field(s) if you think you need one. Write "None" if you don't need one.
B) Complete the constructor so that the first Student object gets York ID York-1, the second Student object gets York-2 etc.
i dont have time. Please be quick
thanks
I am going to answer the question subpart by subpart as it is asked. Before I answer this question, let me clarify that I'm going to use the programming language Java since we haven't been told the programming language but I'll try to make the logic behind this solution clear so that solution could be changed easily.
A)
Yes, the student class would need one more field that is a static field, we can name it however we want but I'm going to name it id and I will instantiate with the value 1 since our yorkId starts with value York-1. A static variable is a type of variable which is shared across all the instances of a class.
B)
Instead of writing only the constructor, I will write the whole class so that there is no confusion in the end.
Student Class :
public class Student
{
// Fields required
String yorkId;
static int id=1;
// Constructor
public Student(){
yorkId="York-"+id;
id++;
}
// Main function to create students and see the yorkId
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
System.out.println("The unique ID
of first student is " + s1.yorkId);
System.out.println("The unique ID
of second student is " + s2.yorkId);
System.out.println("The unique ID
of third student is " + s3.yorkId);
}
}
Code screenshot :
Code output :
The explanation for the constructor :
We are incrementing the static variable Id when an object gets created and then we can concatenate the variable id and "York-" to form our unique id.
Solution ends.
Please comment and let me know if you have any further doubts. Please upvote this answer if you like it.
Thank you.
Have a good day.
Get Answers For Free
Most questions answered within 1 hours.