Can one override in builders?

Asked

Viewed 550 times

5

Is it possible to override in builders? For example:

@Override
public class main (String arg[]){}
  • 1

    Hello @Dr.G, first I want to introduce some areas of the site and strongly recommend that you read and know before asking questions and anything. Make a tour in the Stack and know how to ask a good question

  • 2

    Is that a question already answered? When you extend a class, you must define a new constructor, there is no way to override the constructor of the extended class, as it is not the constructor of the current object. If the language allows (never tested this), that you rewrite(define a method with the extended class name, I doubt it will be invoked when you give new in the object.

  • @Victorgomes is just me or the question is good enough to be on the site...

1 answer

6


The way you’re trying to make it like the constructor is a method is not possible. A builder is not polymorphic and inheritance takes place otherwise.

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

Anyway this will not occur in the method main() who is not a builder of any class. At least as far as you can understand. And if the intention was to create a method in the question, the syntax is all wrong.

Recalling that the @Override is not mandatory.

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();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.