Can you override constructors?

2

I think I can not, what do you have to tell me?

@Override
public class main (String arg[]){}
    
asked by anonymous 12.05.2016 / 21:45

1 answer

4

The way you're trying to do as if the constructor were a method is not possible. A constructor is not polymorphic and inheritance is otherwise.

It can be said that there is an inheritance relationship between the base class constructor and the derived class, after all the constructor of the derived class assumes the main role of construction and then implicitly or explicitly delegates the construction of the base. >

In any case, this will not occur in the main() method, which is not a constructor of any class. At least you can understand. And if the intention was to create a method in the question, the syntax is all wrong.

Remembering that @Override is not required .

class Base {
    Base() {
        System.out.println("Construção Base");
        metodo();
    }
    void metodo() {
        System.out.println("Método em Base");
    }
}

class Derivada extends Base {
    Derivada() {
        System.out.println("Construção Derivada");
    }
    @Override
    void metodo() {
        System.out.println("Método em Derivada");
    }
}

class Ideone {
    public static void main(String args[]) {
        Base base = new Base();
        base.metodo();
        System.out.println("------------------------");
        Derivada derivada = new Derivada();
        derivada.metodo();
    }
}

See working on ideone and CodingGround .

    
12.05.2016 / 22:21