Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. CONSTRUCTOR: The sole purpose of having CONSTRUCTORs is to create an instance of a class. They are invoked while creating an object of a class. CONSTRUCTORs can be public, private, or protected. If a CONSTRUCTOR with arguments has been defined in a class, you can no longer use a default no-argument CONSTRUCTOR you have to write one. They are called only once when the class is being instantiated. They must have the same name as the class itself. They do not return a value and you do not have to specify the keyword void. If you do not create a CONSTRUCTOR for the class, Java helps you by using a so called default no-argument CONSTRUCTOR. public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); CONSTRUCTOR overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows: public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; Boss() { name = "Our Boss is a nice man. We don t call him names. ; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); Boss p2 = new Boss(); 2. What are Class CONSTRUCTORs S.N. 1 2 CONSTRUCTOR & Description String() This initializes a newly created String object so that it represents an empty character sequence. String(byte[] bytes) This constructs a new String by decoding the specified array of bytes using the platform's default
charset. 3 4 String(byte[] bytes, Charset charset) This constructs a new String by decoding the specified array of bytes using the specified charset. String(byte[] bytes, int offset, int length) This constructs a new String by decoding the specified subarray of bytes using the platform's default charset 3. Wha is a Copy CONSTRUCTOR unlike C++, Java doesn t create a default copy CONSTRUCTOR you have to write your own Following is an example Java program that shows a simple use of copy CONSTRUCTOR. // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im; // Overriding the tostring of Object class @Override public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2;//no new, therefore don t need copy CONSTRUCTOR System.out.println(c2); // tostring() of c2 is called here 4. What are the Rules for creating java constructor There are basically two rules defined for the constructor. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type
5. What are the Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor 6. What is a Java Default Constructor A constructor that have no parameter is known as default constructor. 7. What is the Syntax of default constructor: <class_name>(){ 8. Give an Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. class Bike1{ Bike1(){System.out.println("Bike is created"); Bike1 b=new Bike1(); Output: Bike is created Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
9. What is the purpose of default constructor? Default constructor provides the default values to the object like 0, null etc. depending on the type. Example of default constructor that displays the default values class Student3{ int id; void display(){system.out.println(id+" "+name); Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); Output: 0 null 0 null Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.here 0 and null values are provided by default constructor. 10. Java parameterized constructor A constructor that have parameters is known as parameterized constructor. 11. Why use parameterized constructor? Parameterized constructor is used to provide different values to the distinct objects. 12. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4{ int id; Student4(int i,string n){ id = i; name = n; void display(){system.out.println(id+" "+name); Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display();
Output: 111 Karan 222 Aryan
13. What is Constructor Overloading in Java Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.the compiler differentiates these constructors by taking into account the number of parameters in the list and their type. Example of Constructor Overloading class Student5{ int id; int age; Student5(int i,string n){ id = i; name = n; Student5(int i,string n,int a){ id = i; name = n; age=a; void display(){system.out.println(id+" "+name+" "+age); Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); Output: 111 Karan 0 222 Aryan 25 14. Differences Between Constructors and Methods The main difference is Constructor used to initialize the state of object must not have return type name same as the class name invoke implicitly compiler provide default constructor chained in particular order method expose the behaviour of object must have return type may or may not the same class name invoke explicitly compiler does't provide called unlimited number of times using the same object 15. What is a Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are: By constructor By assigning the values of one object into another By clone() method of Object class In this example, we are going to copy the values of one object into another using java constructor. class Student6{ int id; Student6(int i,string n){ id = i; name = n; Student6(Student6 s){ id = s.id; name =s.name; void display(){system.out.println(id+" "+name); Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); Output: 111 Karan 111 Karan 16. Give an example of a Copy CONSTRUCTOR in Java // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im;
// Overriding the tostring of Object class @Override public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // tostring() of c2 is called here 17. Give an example of copying without a constructor We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. class Student7{ int id; Student7(int i,string n){ id = i; name = n; Student7(){ void display(){system.out.println(id+" "+name); Student7 s1 = new Student7(111,"Karan"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); Output: 111 Karan 111 Karan 18. Q) Does constructor return any value? Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
19. Can constructor perform other tasks instead of initialization? Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method. 20. How are this() and super() used with CONSTRUCTORs? this() is used to invoke a CONSTRUCTOR of the same class. super() is used to invoke a superclass CONSTRUCTOR. 21. Calling a CONSTRUCTOR From a CONSTRUCTOR In Java it is possible to call a CONSTRUCTOR from inside another CONSTRUCTOR. When you call a CONSTRUCTOR from inside another CONSTRUCTOR, you use the this keyword to refer to the CONSTRUCTOR. Here is an example of calling one CONSTRUCTOR from within another CONSTRUCTOR in Jav public class Employee { private String firstname = null; private String lastname = null; private int birthyear = 0; public Employee(String first, String last, int year ) { firstname = first; lastname = last; birthyear = year; public Employee(String first, String last){ this(first, last, -1); Notice the second CONSTRUCTOR definition. Inside the body of the CONSTRUCTOR you find this Java statement: this(first, last, -1); The this keyword followed by parentheses and parameters means that another CONSTRUCTOR in the same Java class is being called. Which other CONSTRUCTOR that is being called depends on what parameters you pass to the CONSTRUCTOR call (inside the parentheses after the this keyword). In this example it is the first CONSTRUCTOR in the class that is being called. 22. Calling CONSTRUCTORs in Superclasses In Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. A class that extends another class does not inherit its CONSTRUCTORs. However, the subclass must call a CONSTRUCTOR in the superclass inside one of the subclass CONSTRUCTORs! Look at the following two Java classes. The class Car extends (inherits from) the class Vehicle. public class Vehicle { private String regno = null; public Vehicle(String no) {
this.regno = no; public class Car extends Vehicle { private String brand = null; public Car(String br, String no) { super(no); this.brand = br; Notice the CONSTRUCTOR in the Car class. It calls the CONSTRUCTOR in the superclass using this Java statement: super(no); Using the keyword super refers to the superclass of the class using the super keyword. When super keyword is followed by parentheses like it is here, it refers to a CONSTRUCTOR in the superclass. In this case it refers to the CONSTRUCTOR in the Vehicle class. Because Car extends Vehicle, the Car CONSTRUCTORs must all call a CONSTRUCTOR in the Vehicle. 23. Java CONSTRUCTOR Access Modifiers For instance, if a CONSTRUCTOR is declared protected then only classes in the same package, or subclasses of that class can call that CONSTRUCTOR. A class can have multiple CONSTRUCTORs, and each CONSTRUCTOR can have its own access modifier. Thus, some CONSTRUCTORs may be available to all classes in your application, while other CONSTRUCTORs are only available to classes in the same package, subclasses, or even only to the class itself (private CONSTRUCTORs). 24. Can a CONSTRUCTOR be made final? No, this is not possible. 25. What's the difference between CONSTRUCTORs and other methods? CONSTRUCTORs must have the same name as the class and cannot return a value. They are only called once while regular methods could be called many times. 26. Can you call one CONSTRUCTOR from another if a class has multiple CONSTRUCTORs? Yes, use this() syntax. 27. Can CONSTRUCTOR be inherited? No, CONSTRUCTOR cannot be inherited. 28. Where and how can you use a private CONSTRUCTOR? Private CONSTRUCTOR is used if you do not want other classes to instantiate the object and to prevent subclassing. 29. What s the point of having a private CONSTRUCTOR? This may be news to you: in Java, it is possible to have a private CONSTRUCTOR. Why one would want to use one is explored below. The private modifier when applied to a CONSTRUCTOR works in much the same way as when applied to a normal method or even an instance variable. Defining a CONSTRUCTOR with the private modifier says that only the native class (as in the class in which the private CONSTRUCTOR is defined) is allowed to create an instance of the class, and no other caller is
permitted to do so. There are two possible reasons why one would want to use a private CONSTRUCTOR 3. first is that you don t want any objects of your class to be created at all, and the 4. second is that you only want objects to be created internally as in only created in your class. 30. Private CONSTRUCTORs can prevent creation of objects The other possible reason for using a private CONSTRUCTOR is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn t make sense and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name no instance of the class needs to be created. Java always provides a default, no-argument, public CONSTRUCTOR if no programmerdefined CONSTRUCTOR exists. Creating a private no-argument CONSTRUCTOR essentially prevents the usage of that default CONSTRUCTOR, thereby preventing a caller from creating an instance of the class. Note that the private CONSTRUCTOR may even be empty 31. Can an INTERFACE extend another INTERFACE? Yes an INTERFACE can inherit another INTERFACE, for that matter an INTERFACE can extend more than one INTERFACE. 32. If a method is declared as protected, where may the method is accessed? A protected method may only be accessed by classes or INTERFACES of the same package or by subclasses of the class in which it is declared. 33. What is CONSTRUCTOR chaining and how is it achieved in Java? A child object CONSTRUCTOR always first needs to construct its parent. In Java it is done via an implicit call to the no-args CONSTRUCTOR as the first statement.