Automation QA Testing Course Content

Java OOPS - Constructor/Inheritance


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.

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
3.   A Java constructor cannot be abstract, static, final, and synchronized

Types of java constructors

There are two types of constructors:
1.   Default constructor (no-arg constructor)
2.   Parameterized constructor
java constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

1.   Accessmodifier  <class_name>(){l+s}  

NOTE:  If there is no constructor in a class, compiler automatically creates a default

constructor.

If a class has default constructor, while creating object for the class no need to
provide any parameter values.
Classname refvar=new classname();

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on
 the type.

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.
2.   Accessmodifier  <class_name>(datatype p1,datatype p2,…){l+s}  

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects
If a class has parameterized constructor, while creating object for the class need to provide
 parameter values.
Classname refvar=new classname(p1value,p2value,p3 value);

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 and datatype.The compiler differentiates
 these constructors by taking into account the number of parameters in the list and their
 type.

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.
Java Constructor
Java Method
Constructor is used to initialize the state of an object.
Method is used to expose behaviour of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class name.
Method name may or may
 not be same as class name.

Quiz On Constructor:
1)public class Test{

void Test{
System.out.println("Like ThisVideo");
}

public static void main(String[] args){
new Test();
}


}
1)Like ThisVideo
ii)No Output
iii)Exception will be thrown
iv)compilation issue
2)