Abstract class with constructor

19

Can a clase abstracta of Java have constructor ?

And if so, what are your goals?

    
asked by Santi92 02.12.2015 в 13:55
source

3 answers

23

Short answer: YES , the abstract classes can have constructors, but ONLY to be used from the constructors of the daughter classes, you can not use them directly because by definition JLS (§8.1.1.1) can not instantiate an abstract class.

Explanation of use

Think of the case of an abstract class where you have to initialize its attributes. If you had an empty constructor it would implicitly be done in the daughter class, otherwise we must use super(param1, param2); to specify it. A constructor with parameters in an abstract class, what it does is force the daughter class to specify parameters.

Practical example:

abstract class Persona {
   private String nombre;

   // declaracion del constructor de la clase abstracta por lo que implicitamente 
   //estamos omitiendo el constructor por defecto public Person() obligando a las
   // clases hijas a llamar a este constructor con parametros.
   public Person(String nombre) {
      this.nombre = nombre;
   }
}

class Estudiante extends Persona {
   public Estudiante(String nombre) {
     // uso del constructor de la clase abstracta
     super(nombre);   
   }
}

// finalmente puedes realizar la abstraccion con Estudiante y Persona
Person p = new Estudiante("Manuel");
    
answered by 02.12.2015 / 14:01
source
3

Of course you can:

abstract class Producto { 
    int multiplicadoPor;
    public Producto( int multiplicadoPor ) {
        this.multiplicadoPor = multiplicadoPor;
    }

    public int multiplicar(int valor) {
       return multiplicadoPor * valor;
    }
}

class MultiplicadoPorDos extends Producto {
    public MultiplicadoPorDos() {
        super(2);
    }
}

class MultiplicadoPorX extends Producto {
    public MultiplicadoPorX(int x) {
        super(x);
    }
}

Abstract classes always have a constructor. If you do not specify one then one is created by default and without arguments, as with any other class. In fact, ALL classes, including nested and anonymous classes, will have a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one so that you will always have the constructor created by default ).

The constructor of the abstract classes behaves in the same way as any other constructor, the difference is that these classes can not be directly instantiated only extended.

Reference:

answered by 02.12.2015 в 14:00
1

In a class to be abstract you need at least to have an abstract method.

The idea that a class is abstract is that it has abstract methods to be implemented and overwritten by the classes that inherit from the abstract class and thus apply, if required by business logic, polymorphism.

    
answered by 16.12.2015 в 01:41