Constructors in java

Hello friends sorry I am studying java and in the classes the teacher touched on the topic of "java constructors" and the truth I did not understand well.

Well what I understood is this:

A constructor is similar to a method but only serves to initialize objects, it does not return any type of return value and a constructor serves to initialize the value of an object.

 15
Author: lois6b, 2016-10-06

9 answers

In java a constructor is a kind of method that allows you to initialize the attributes of a class.

public class Persona {

    private String nombre;
    private String apellido;

    public Persona(){

    }

    public Persona(String nombre, String apellido){
        this.nombre = nombre;
        this.apellido = apellido;
    }

    // Getters y Setters irían aquí abajo ...
}

As you can see in the person class there are two constructors, one without parameters

  public Persona() {  
  }

And another with parameters

public Persona(String nombre, String apellido){
   this.nombre = nombre;
   this.apellido = apellido;
}

The Main class would look like this:

public class Main {

    public static void main(String[] args) {

        Persona persona1 = new Persona();
        persona1.setNombre("Antonio");
        persona1.setApellido("Morales");

        Persona persona2 = new Persona("Luis", "Veliz");

        System.out.println(persona1.getNombre());
        System.out.println(persona2.getNombre());
    }
}

The output would be this:

Antonio
Luis

As you can see for the person2 object we did not have to access the get and set methods to give value to their attributes since we create it from the constructor with parameters.

In a class you can have as many constructors as you want as long as the parameters they receive are different from those of other constructors, either in quantity or type, that is, in the person class we could have:

public Persona(String nombre){
    // Código
}

public Persona(String apellido, int cualquierVariable){
    // Código
}

public Persona (Boolean cualquierOtraVariable) {
   // Código
}
 12
Author: Luis Veliz, 2016-10-06 04:26:59

What you understood is correct!

A constructor is similar to a method but serves to initialize objects does not return any type of return value

The definition of the documentation tells Us:

A constructor is used in the creation of an object that is a instance of a class. Usually carries out operations required to initialize the class before the methods are invoked or accessed field. Builders are never inherited.

Based on this we can define characteristics and differences with respect to a method:

  • a constructor must always have the same name as the class.
  • a constructor does not have a return type so it does not return any value. A method may or may not have a return value type.
  • a constructor is called when an object is instantiated, and this is only done once, unlike methods that can be called on multiple occasions.
  • constructors are never inherited, as they are not considered class members. This is an important difference from the methods as these if could be inherited.
  • when we inherit from a base class, if a constructor is not declared, java automatically calls the default constructor of the class we inherit.

This is an example of a class where we reference the constructor:

public class Pais { 

    private String nombre; //propiedad nombre de cada objeto Pais. 
    private int cantidadHabitantes; //propiedad cantidadHabitantes de cada objeto Pais. 

    //Constructor, cuando se cree un objeto Pais se ejecutará el código incluido en el constructor, como sabemos sirve para INICIALIZAR.
    public Pais (String nombre, int cantidadHabitantes) {
        this.nombre = nombre;
        this.cantidadHabitantes = cantidadHabitantes ;
        //Puedes inicializar también con un valor fijo. 
        //this.nombre = "México City";
        //this.cantidadHabitantes = 125000;
    } 

      //Getters/Setters
      //método para obtener nombre de pais en el objeto Pais.
    public String getNombre () { return nombre; } 
    //método para asignar nombre pais en el objeto Pais.
    public void setNombre(String nombre){
            this.nombre = nombre;
    }

    //método para obtener cantidad de habitantes de pais en el objeto Pais.
    public int getCantidadHabitantes () { return cantidadHabitantes; } 
    //método para asignar cantidad de habitantes de pais en el objeto. 
    public void setCantidadHabitantes(int cantidadHabitantes){
            this.cantidadHabitantes = cantidadHabitantes;
    }


} 

I add an interesting article in Spanish: definition of constructors of a class.


Add to the object the get and set methods, which are simple methods we use in classes to display (get method) or modify (set method) the value of an attribute in the class .

 9
Author: Jorgesys, 2016-10-07 01:52:12

¿ What is a builder?

Is a method-like block of code that is called when an object is instantiated .

¿ What makes it different from a method ?

  • A constructor does not have a return type.

  • The constructor name must be the same as the class name.

  • Unlike methods, constructors are not considered members of a class.

  • A constructor is called automatically when a new instance of an object is created.

Structure of a Constructor

 /* La palabra reservada public indica que otras clases 
    pueden tener acceso al constructor */
 public NombreClase (TipoDato nombreparam1,TipoDato nombreparam2) 
    /* Parametros Separados por Coma */
 {
     /* Declaraciones y/o asignaciones */
 }

A constructor allows you to provide initial values for the fields(attributes) of the class when an object is instantiated.

 public class Persona {
   /* Atributos */
   private String nombre; 
   private String apellido;

  /* En el Constructor de la Clase Persona Inicializamos  los atributos 
      nombre y apellido  asigname a nombre el valor de name que es enviado
        al instanciar un Objeto de la clase Persona */
  public Persona(String name, String lastname)
  {
   this.nombre = name;
   this.apellido = lastname;
  }

}

Instances are created as follows , this will cause the constructor that receives two type parameter to be automatically called String

Persona per = new Persona("Nombre1", " Apellido1");
/* tu objeto Persona tendrá sus atributos nombre= Nombre1 y 
   apellido = Apellido1 */

To read this a little more thoroughly , it is important and always essential to read the documentation. https://docs.oracle.com/javase/tutorial/reflect/member/ctor.html

A little deeper https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Constructor.html

 6
Author: Dev. Joel, 2016-10-06 20:21:28

Its function is to initialize the attributes and objects that a class has since if they are not initialized it can cause an exception of the type NullPointerException let's see an example

public class Ciudad{
  private int codigo;


  //aqui el constructor
  public Ciudad(){
   codigo="123"; //asignaste el valor 123 a la variable codigo

   //tambien puedes ejecutar otros metodos esto se hace generalmente cuando quieres que se ejecute una accion al arrancar la aplicacion por ejemplo que muestre un mensaje de bienvenida en consola
   System.out.println("bienvenido");
  }
}

If you create an object of this class you will see that the code is initialized to 123 and the message is displayed in the lucky console!

 4
Author: Jesus Antonio Quintero Cardona, 2017-04-10 20:53:06

According to my perspective and in order to contribute to your doubt

A constructor, as the name says, is a block of code that takes care of instantiating or initializing an object of a given class. Each class has or should have certain attributes that differentiate it from other classes (hence from other objects). Constructors do not have a type (void, static, etc) or return a value, their function is always to initialize all properties or attributes of the class in question. They do not necessarily always have to carry specific values, for example, a value of a property if we wish (although I do not see the case well) we can start it as null in case of objects, in 0 in types numbers or in "" in text types. There are two types of constructors, with and without parameters.

Example:

We have a class called Auto with two attributes (or properties): plate and Mark

Note: If you don't give it an access modifier (private, public, protected) by default only the own class and package can access that property.

  1. not specified
    • can access: class and package
  2. Private
    • can be accessed: only the class
  3. Protected
    • can access: the class, package and a subclass (in case of inheritance)
  4. Public
    • can access: all (class, subclass, package, etc)

Example:

public class Auto{
    String placa;
    String marca;

    public Auto () {
    }

    public Auto (String placa, String marca){
        this.placa = placa;
        this.marca = marca;
    }
}

In this particular case, the input parameters of the constructor have the same names as the properties of the class. That's why I use the this to refer to the properties of your class, although it can also be like this:

public Auto (String placaAuto, String marcaAuto){
    placa = placaAuto;
    marca = marcaAuto;
}

For the creation of an Auto type object, as I explain above depending on the access modifier is how you can create it

If the indicators of the properties carry public or do not carry can be

Auto nuevoAuto = new Auto();
nuevoAuto.placa = "HV-45-78";
nuevoAuto.marca = "Chevrolet";

Or

Auto nuevoAuto = new Auto("HV-45-78", "Chevrolet");

Both forms are valid and will help you instantiate an object of type Auto, I hope this information will help you and complement those that the others gave you.

 3
Author: sioesi, 2016-10-12 20:33:11

Provide constructors for the classes a class contains constructors that are invoked to create objects from the model classes. declaration of builders look like declarations method, except that use the class name and do not have any kind of return. For example, the bike has a builder: Public bicycle (int startCadence, int Startspeed, int startGear) {gears = startGear; cadence = startCadence; speed = Startspeed;} to create a new object of bicycles called myBike, a builder is called by the new operator: Bicycle myBike = new bicycles (30, 0, 8); newBicycle (30, 0.8) create a space in memory for the object and initializes its field. Despite bikes it only has one constructor, which could have others, including a constructor without arguments.

Thanks for the feedback

 1
Author: Sommer, 2016-10-12 20:07:05

A constructor provides the initial state of an object. Think of an object, for example, the Auto class with properties: Marca, Modelo, Kilometraje and Color. When you create an object of this class you have to give the values for those properties Example:

Auto carro1= new Auto("Ford", 2012, 56000, "verde")

By giving those values the object is constructed with those characteristics.

This statement new Auto("Ford", 2012, 56000, "verde") calls the constructor and tells it the values that the object carro1

 1
Author: Alberto Saucedo, 2018-10-12 00:59:23

Everything is very simple, more than it seems. A Java variable stores references to objects, which for a lifetime has been called a pointer. Initially, uninitialized contains garbage, namely it will be an unsafe element to use.

You need to have an object, but you can only get it from a constructor, which is the mechanism that allows you to create the reference that will save the variable. Thanks to the constructor, the memory space of the Pointer is reserved and it is given the initial values with which the object begins to work.

The constructor, therefore, is the means by which objects are obtained for a class.

 0
Author: AmbarJ2009, 2016-10-12 17:28:20

I'm also new to this programming, but I share what I understand:

The constructor, as your teacher effectively says, initializes the values of the attributes your class has and initializes the object.

What does this mean?

Agree that variables and objects are pointers. Think of it as a label, which we use to identify x variable and be able to use it correctly in our program but, BUT, BUT!!! for the computer, that "Label" contains an" address " (in hexadecimal)which tells you in which memory space the value of our variable is stored so it knows where it has to go to look for the value we want and not another.

When we create / instantiate an object, space is reserved in memory for all the parameters it contains. Ex: class person has: String first name, string last name, int age, boolean sex, etc... They are reserved a space in memory for each one of these parameters is initialized.

2 things:

  1. When we declare that a variable, for example "string name" is equal to NULL (name = null;). We tell you that our marker is not pointing anywhere! That is, it has no address in memory, so it does not exist in our memory. That is, it is not "initialized"... Usefulness of this? Null is used a lot for Dynamic Data Structures (lists, trees), where the correct usage the null modifier is vital not to get into infinite loops when a node is instantiated.

  2. Primitive data types, if not instances, acquire a default value. That is, byte, int, long, double, float, boolean, char, etc, all these have a default value, such as the booleans that by default are instantiated to false. But structured or class data types, such as the case of our beloved STRING (String is an object, when you value a String variable, this creates a STRING of characters (char) and creates an object) MUST BE INITIALIZED, but when you want to use in your program (without being initialized), you will throw the error: NULLPOINTER EXCEPTION, that is to say that our pointer will not point to any side, because it is not assigned a value when we create our object. If you think about it, this is what happens with an ARRAY, when we declare the size, but don't initialize it / loop through Space x space for assign value to it.

IN SHORT

So the constructor, what it does is reserve space in memory for our object giving each of its fields a default value (which we define in the constructor, e.g. age = 0;), which we can then modify at will to do, whatever we want to do in our program.

 0
Author: Franco Garcia, 2020-11-03 15:11:19