Given1. class Person{2. //What would be correct constructor for this class3. } What would be correct constructor for Person class?*Person(){ System.out.print(“Person”); } // new return line super();void Person(String s){ }final Person(){ System.out.print(“Person”); //new return line }Persons(){ }private Person(int x){ }
Question
Given1. class Person{2. //What would be correct constructor for this class3. } What would be correct constructor for Person class?*Person(){ System.out.print(“Person”); } // new return line super();void Person(String s){ }final Person(){ System.out.print(“Person”); //new return line }Persons(){ }private Person(int x){ }
Solution
The correct constructor for the Person class would be:
public Person() {
System.out.print("Person");
}
Here's why:
- The constructor name must match the class name, which is "Person" in this case.
- Constructors do not have a return type, so "void" and "final" are not appropriate.
- The "super()" call is not necessary in this case because the Person class does not extend any other class.
- The constructor can have any access modifier. In this case, "public" is used, meaning the constructor is accessible from any class. If you want the constructor to be accessible only within the same class, you can use the "private" modifier.
- The constructor can also take parameters, like "String s" or "int x", if you need to initialize some fields of the Person class. But in this case, no parameters are needed.
Similar Questions
Which of the following is the correct way to declare a constructor in Java?Question 1Answera.MyClass = new Constructor { }b.void MyClass( ) { }c.constructor MyClass( ) { }d.MyClass ( ) { }
Which of the following is not a valid constructor declaration in Java?a.protected ClassName() {}b.public ClassName() {}c.ClassName void() {}d.private ClassName() {}
Which of the following statements about constructors is/are correct?Options: Pick one correct answer from belowThe constructor name should be the same as the class name.The default constructor invokes super() and sets all instance variables to a default value such as 0, null.If we do not define a constructor for a class, the compiler will generate one for usIf we want to call parent class constructor, we must call it in the constructor's first line.All the above
Which of these classes compile and use a default constructor? (Choose all that apply)*A. public class Bird { }B. public class Bird { public bird() {} }C. public class Bird { public bird(String name) {} }D. public class Bird { public Bird() {}E. public class Bird { Bird(String name) {} }F. public class Bird { private Bird(int age) {} }G. public class Bird { void Bird() { }
24. Which among the following represents correct constructor?a) –classname()b) classname()c) ()classnamed) ~classname()
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.