Computer Applications
Consider the following Java class and answer the questions given below:
class Student
{
String name;
int age;
Student(String n, int a)
{
name = n;
age = a;
}
void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args)
{
Student s1 = new Student("John", 15);
Student s2 = new Student();
s1.display();
s2.display();
}
}
(a) Will this program compile successfully? If not, explain the error.
(b) How can this program be modified to work correctly?
Java Constructors
6 Likes
Answer
(a) No, it will not compile because the class does not have a default constructor.
(b) To fix the issue, a default constructor must be added.
Reason — The given Java program will not compile successfully because the Student class has a parameterized constructor but does not have a default constructor. In the main method, an object s2 is being created using new Student();, which tries to call a default constructor. Since no default constructor is explicitly defined, and Java does not provide one when a parameterized constructor is present, this results in a compilation error.
Answered By
1 Like