Un constructor en Java es un método especial que se usa para inicializar un objeto. Cada vez que se crea un objeto usando la nueva palabra clave, se llama al menos una construcción. El nombre del constructor debe coincidir con el nombre de la clase y no puede tener un tipo de retorno. Si no hay un constructor disponible en la clase, en tal caso, el compilador de Java proporciona un constructor predeterminado (sin constructor de parámetros) de forma predeterminada.
Constructor Parametrizado: El constructor parametrizado se utiliza para inicializar el campo de la clase con nuestros propios valores.
Ejemplo:
Java
// Parameterized Constructor Example in Java import java.io.*; class parameterizedConstructor { // fields of the class String name; int regestrationNumber; // creating a parameterized constructor so that we can // initialize the value of the class parameterizedConstructor(String name, int regestrationNumber) { System.out.println("constructor call"); this.name = name; this.regestrationNumber = regestrationNumber; } } class GFG { public static void main(String[] args) { // creating our first object parameterizedConstructor obj1 = new parameterizedConstructor("Nilesh", 2021806); System.out.println("Name of the student " + obj1.name); System.out.println("Registration Number " + obj1.regestrationNumber); // creating second object parameterizedConstructor obj2 = new parameterizedConstructor("Bhaskar", 2021807); System.out.println("Name of the student " + obj2.name); System.out.println("Registration Number " + obj2.regestrationNumber); } }
constructor call Name of the student Nilesh Registration Number 2021806 constructor call Name of the student Bhaskar Registration Number 2021807
En una jerarquía de clases, los constructores se llaman de acuerdo con la jerarquía, se invocará el primer constructor de la clase principal y luego se invocará el constructor de la clase secundaria.
Ejemplo 1
Java
// Java Program to Allocate and Initialize Super Class // Members Using Constructor import java.util.*; class y { int b; int c; // parameterized constructor of class y y(int b, int c) { this.b = b; this.c = c; System.out.println("Hi I am parent constructor"); System.out.println("multiplication of two number " + b + " and " + c + " is " + b * c); } } class x extends y { int a; // parameterized constructor of class x x(int b, int c, int a) { // calls constructor of y super(b, c); System.out.println( "Hi I am child class constructor"); System.out.println("class field of x class is " + a); } } class GFG { public static void main(String[] args) { // creating an object of class x // this will invoke the constructor of x // but before invoking the constructor of class x // it will invoke the constructor of it's parent // class which is y x obj = new x(3, 4, 5); } }
Hi I am parent constructor multiplication of two number 3 and 4 is 12 Hi I am child class constructor class field of x class is 5
Ejemplo 2
Java
// Java Program to Allocate and Initialize Super Class // Members Using Constructor import java.io.*; class grandParent { int grandParentAge; String grandParentName; // constructor grandParent(int grandParentAge, String grandParentName) { this.grandParentAge = grandParentAge; this.grandParentName = grandParentName; } } class parent extends grandParent { int parentAge; String parentName; // parameterized constructor parent(int grandParentAge, String grandParentName, int parentAge, String parentName) { // calls grandparent constructor super(grandParentAge, grandParentName); this.parentAge = parentAge; this.parentName = parentName; } } class child extends parent { int childAge; String childName; // constructor child(int grandParentAge, String grandParentName, int parentAge, String parentName, int childAge, String childName) { // calls parent constructor super(grandParentAge, grandParentName, parentAge, parentName); this.childAge = childAge; this.childName = childName; } public void dispalyDetails() { System.out.println("Name of grand parent " + grandParentName + " and he is " + grandParentAge + " year old"); System.out.println("Name of parent " + parentName + " and he is " + parentAge + " year old"); System.out.println("Name of child " + childName + " and he is " + childAge + " year old"); } } class GFG { public static void main(String[] args) { // creating an object of class child // this will invoke the constructor of child // but before invoking the constructor of class // child it will invoke the constructor of it's // parent class which is parent but parent is child // of grandparent class so, before invoking the // constructor of parent class it will invoke the // constructor of grandparent class child obj = new child(85, "Pan Singh", 39, "M.S.Dhoni", 5, "Ziva Dhoni"); obj.dispalyDetails(); } }
Name of grand parent Pan Singh and he is 85 year old Name of parent M.S.Dhoni and he is 39 year old Name of child Ziva Dhoni and he is 5 year old