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
1 Like
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
Related Questions
Consider the given program and answer the questions given below:
class temp { int a; temp() { a=10; } temp(int z) { a=z; } void print() { System.out.println(a); } void main() { temp t = new temp(); temp x = new temp(30); t.print(); x.print(); } }
(a) What concept of OOPs is depicted in the above program with two constructors?
(b) What is the output of the method main()?
Explain the following terms:
Copy constructor
Assertion (A): The default constructor initializes object fields to zero or null depending on their data type.
Reason (R): Java constructors are inherently tied to the initialization of an object and therefore do not specify a return type.
Fill in the blanks:
The _________ refers to the current object.