Given the code fragment
What is the result?
A. Compilation fails at both line n1 and line n2
B. Compilation fails only at line n2.
C. Compilation fails only at line n1.
D. Jesse 25 Walter 52
Given the code fragment
What is the result?
A. Compilation fails at both line n1 and line n2
B. Compilation fails only at line n2.
C. Compilation fails only at line n1.
D. Jesse 25 Walter 52
A
public class Person {
String name;
int age = 25;
public Person(String name) {
this();
setName(name);
}
public Person(String name, int age) {
Person(name);
setAge(age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String show() {
return name + ” ” + age + ” ” + number;
}
public static void main(String[] args) {
Person pl = new Person(“Jesse”);
Person p2 = new Person(“Walter”, 52);
System.out.println(pl.show());
System.out.println(p2.show());
}
}
A:
# javac Person.java
Person.java:6: error: no suitable constructor found for Person()
this();
^
constructor Person.Person(String,int) is not applicable
(actual and formal argument lists differ in length)
constructor Person.Person(String) is not applicable
(actual and formal argument lists differ in length)
Person.java:11: error: cannot find symbol
Person(name);
^
symbol: method Person(String)
location: class Person
Person.java:12: error: cannot find symbol
…….
Answer A:
To call a constructor from another constructor, we have to use the keyword “this()”, and it should be the first line in the calling constructor body.
In line 1, we are calling a no-args constructor, which is not defined explicitly. And since we already have other constructors, JVM will not supply the default no-args constructor for us. Accordingly, the “this()” call is directly the compiler to a non-existent constructor, leading the compilation to fail at line 1.
In line 2, we are calling a constructor that takes “name” as an argument. Although this constructor is available, but referring to it is not correct. Line 2 would compile if we say “this(name)” instead of “Person(name)”.
1.error: no suitable constructor found
2. error: cannot find symbol
it’s a
After typing it’s A
I typed the code in Eclipse then line n1 and line n2 gave a compilation error. Therefore, answer should be A
C