Builders in java

14

Hello friends, sorry, I am studying java and in the classes the teacher touched on the topic of "java builders" and I did not really understand it.

Well what I understood is this:

  

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

    
asked by Sommer 06.10.2016 в 03:31
source

8 answers

10

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 realize for the person2 object, we did not have to access the get and set methods to give value to its attributes since we created 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
}
    
answered by 06.10.2016 в 06:26
8

What you understood is correct!

  

A constructor is similar to a method but it is used 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. Generally carries out operations   required to initialize the class before the methods are   invoked or accessed fields. The 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 type of return value.
  • A constructor is called when an instance of an object is created, and this is only done once, unlike methods that can be called multiple times.
  • Constructors are never inherited, since they are not considered as class members. This is an important difference with respect to the methods since these 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 that we inherit.

This is an example of a class where we refer to 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 builders of a class.

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

    
answered by 06.10.2016 в 14:52
6

What is a Constructor?

  

It is a block of code similar to a method that is called when an instance of an object is created.

What sets it apart from a Method?

  • A constructor does not have a return type.

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

  • Unlike methods, builders do not consider themselves 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 automatically call the constructor that receives two parameters of type String

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

To read a little more thoroughly this, it is important and always essential to read the documentation. link

Something more in depth link

    
answered by 06.10.2016 в 06:17
3

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 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 in 123 and the message is displayed in the lucky console!

    
answered by 10.04.2017 в 22:53
2

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

A constructor, as its name says, is a block of code that is responsible for creating an instance or initializing an object of a given class. Each class has or should have certain attributes that differentiate it from other classes (hence other objects). Constructors have no type (void, static, etc) nor return a value, its function is to always initialize all the properties or attributes of the class in question. Not necessarily always have to carry specific values, for example, a value of a property if we want (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 types of text . There are two types of builders, with and without parameters.

Example:

We have a class called Auto with two attributes (or properties): Badge and Brand

Observation: If you do not give an access modifier (private, public, protected) by default only the own class and the package can access that property.

  • Not specified
    • You can access: The class and the Package
  • Private
    • You can access: only the class
  • Protected
    • You can access: The class, the package and a subclass (in case of inheritance)
  • Public
    • You 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 of the properties of the class. That's why I use the this to make specific reference 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 object type Auto, as I explained above depending on the access modifier is how you can create it

    If the property indicators are public or not, it may be

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

    O

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

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

        
    answered by 12.10.2016 в 22:33
    1

    Provide builders for Classes A class contains constructors that are invoked to create objects from class model. declarations of builders look like declarations method, except that use the name of the class and they do not have any kind of return. For example, the bicycle has a builder: Public bicycle (int startCadence, int Startspeed, int startGear) {gears = startGear; cadence = startCadence; speed = Startspeed; } To create a new bicycle object called myBike, a constructor 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 initialize its fields Despite bicycles you only have one builder, who could have others, including a constructor without arguments.

    Thanks for the comments

        
    answered by 12.10.2016 в 22:07
    0

    Everything is very simple, more than it seems. A Java variable stores references to objects, which throughout life have been called pointers. Initially, without initializing it contains garbage, namely, it will be an insecure element to use.

    You need to have an object, but you can only obtain it from a constructor, which is the mechanism that allows you to create the reference that the variable will keep. 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.

        
    answered by 12.10.2016 в 19:28
    0

    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 built with those characteristics.

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

    will have     
    answered by 12.10.2018 в 01:32