Suppose we want to define a class Student that can store the student ID and the
ID: 3677853 • Letter: S
Question
Suppose we want to define a class Student that can store the student ID and the name of the student, and allows us to assign value in initialization. Select all correct implementations from the following options:
Question 1 options:
(1)public class Student {
private int studentId;
private String name;
public Student(int newStudentId, String newName)
{
studentId = newStudentId;
name = newName;
}
}
(2)public class Student {
private int studentId;
private String name;
public void Student(int studentId, String name)
{
this.studentId = studentId;
this.name = name;
}
}
(3)public class Student {
private int studentId;
private String name;
public Student(int studentId, String name)
{
studentId = studentId;
name = name;
}
}
(4)public class Student {
private static int studentId;
private String name;
public Student(int newStudentId, String newName)
{
studentId = newStudentId;
name = newName;
}
}
(5)public class Student {
private int studentId;
private String name;
public Student(int studentId, String name)
{
this.studentId = studentId;
this.name = name;
}
}
(1)public class Student {
private int studentId;
private String name;
public Student(int newStudentId, String newName)
{
studentId = newStudentId;
name = newName;
}
}
(2)public class Student {
private int studentId;
private String name;
public void Student(int studentId, String name)
{
this.studentId = studentId;
this.name = name;
}
}
(3)public class Student {
private int studentId;
private String name;
public Student(int studentId, String name)
{
studentId = studentId;
name = name;
}
}
(4)public class Student {
private static int studentId;
private String name;
public Student(int newStudentId, String newName)
{
studentId = newStudentId;
name = newName;
}
}
(5)public class Student {
private int studentId;
private String name;
public Student(int studentId, String name)
{
this.studentId = studentId;
this.name = name;
}
}
Explanation / Answer
Only 1 and 5 are correct implementations.
Errors in each of 2, 3 and 4 are explained below.
2) A Class constructor should not have a return type.
Example 2 has: public void Student(int studentId, String name)
It should have been public Student(int studentId, String name)
3)
public Student(int studentId, String name)
{
studentId = studentId;
name = name;
}
The compiler is confused between the function parameters and class variables.
4) studentId is a static variable.
private static int studentId;
static variables cannot be initialized in a function, the must be initialized in the class deifinition itself.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.