What is wrong in the following code? public class TempClass { int i; public void
ID: 3726137 • Letter: W
Question
What is wrong in the following code?
public class TempClass {
int i;
public void TempClass(int j) {
this.i = j;
}
}
//------------------------------
public class C {
public static void main(String[] args) {
TempClass temp = new TempClass(2);
}
}
The program has a compilation error because TempClass does not have a default constructor
The program has a compilation error because TempClass does not have a constructor with an int argument.
The program compiles and runs fine.
The program would be fine if the void keyword is removed from public void TempClass(int j).
A)The program has a compilation error because TempClass does not have a default constructor
B)The program has a compilation error because TempClass does not have a constructor with an int argument.
C)The program compiles and runs fine.
D)The program would be fine if the void keyword is removed from public void TempClass(int j).
Explanation / Answer
Correct Options/Answer:
(B): The program has a compilation error because TempClass does not have a constructor with an int argument.
(D): The program would be fine if the void keyword is removed from public void TempClass(int j).
Explaination : First know the definition of constructor -
Constructor: Constructor is used to assign values to the instance variables while instantiation .
Rules for Constructor:
1. Constructor name must be similar to Class name
2. It may or may not take input as parameters
3. Constructor does not have return type.
Constructor are of two types
(1) Default Constructor/Non-paramterised: Constructor that has no parameters . So if you define your constructor without parameters then compiler calls your constructor else compiler calles defalut constructor.
Default constructor assigns the default values -like 0 to int, null to string etc.
ex-
public class TempClass{
int i;
public TempClass() //NO parameters
{
i=10;
}
}
(2) Parameterised Constructor: When constructor has parameters to assign values to the class variables
ex-
public class TempClass{
int i;
public TempClass(int x) //with paramter x;
{
i=x;
}
}
//correct solution is ;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.