214k views
1 vote
What is wrong in the following code? class TempClass { int i; public void TempClass(int j) { int i = j; } } public class C { public static void main(String[] args) { TempClass temp = new TempClass(2); } }

User New Thrall
by
3.5k points

1 Answer

5 votes

Answer:

In the given program, a parameterized constructor declaration is wrong, which can be described as follows:

Step-by-step explanation:

Code:

class TempClass //defining class TempClass

{

int i; //defining integer varaible i

TempClass(int j)//defining parameterized constructor

{

i = j; //variable holds a value

System.out.print(i); //print value

}

}

public class Main //defining class Main

{

public static void main(String[] aw) //defining main method

{

TempClass temp =new TempClass(2); //creating class Object and call parameterized constructor.

}

}

Description:

  • In the given java code, two classes "TempClass and Main" is defined, inside the TempClass class an integer variable "i" and a parameterized constructor is declared, inside the constructor integer variable "i" hold constructor parameter value, the use print method to prints its value.
  • Then the main class is defined, inside this main method is declared, in this method, the TempClass object "temp" is defined, that call the parameter constructor.
User Clairestreb
by
3.8k points