Extend x Superscript, what’s the difference?

Asked

Viewed 570 times

13

Researching on concepts of Object Orientation, I came across the following comparative, Extend (Heritage) versus Superscript.

I found the following statement for this comparative:

Extend:

When we include new attributes, methods in a daughter class.

Overwrite

If we redefine existing (inherited) methods in a daughter class

This definition was not clear in my view. What is the difference between Extend and Superscript in Object Orientation?

  • 8

    When you put in some external information make sure we can easily access it. Otherwise it is irrelevant to say where you took it. It might even look like spam, even if you don’t mean to. Remember that most courses on the internet, paid or free, teach only the basics and often the wrong way. In general, none is worth it. but for an introduction. This if you have a critical sense. If you trust the courses, you are screwed.

  • Got it, thanks for your feedback @bigown. I’ll edit my question.

4 answers

10


Extend (extend) is a class concept and broader. You extend a class by probably putting new members (not just attributes) into it or doing something else in existing methods. Whenever we create a class inheriting from another we intend to extend the class in some way.

Overwrite (override) is a method concept and more specific. You overwrite an existing method in an inherited class, i.e., you make the implementation contained in the current class method to be used in place of the existing implementation in the inherited class. Some languages do this implicitly and others require the explicit desire for superscription, since otherwise the superscript could happen by accident, without the desire of the programmer.

See the example in fictitious language (the rules of each language may vary):

class A {
    metodo1() { print "A"; }
    metodo2() { print "A"; }
}

class B extends A {
    override metodo1() { print "B"; }
    metodo2() { print "B"; }
}

A a = new A().metodo1(); //imprime A
A b = new B().metodo1(); //imprime B, note que o tipo é A, mas a implementação é B
A c = new B().metodo2(); //imprime A, o tipo é A e o método não foi sobrescrito

Read more about the override and your optionality in Java.

An addendum: I did a test with Java and C#. I knew how the second behaved but was not sure of the first.

The above example works well for C#. Does what I said and gives a Warning which is probably not what you want.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Java has made the override even if you can’t.

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

But the answer still holds. Is that now I know that Java does the override implicit where it should not. keep this in mind when programming in Java.

  • 1

    I was left with a doubt, in lines A b = new B(). methodo2(); and A c = new B(). methodo2(); shouldn’t both print "B"? Why do b and c not point to an object of B, whose method2() printa "B"? I was confused by the comments of the lines

  • 2

    Oops. Had a typo. Comments are right. Just note that the c in Java, will print B, what I consider a language error. Learn to live with this if you continue programming in Java. This is not Overriding , that is to say shadowing. It seems to be the same thing, but almost never the programmer wants to shadow the mother class method. And it’s more serious because even if you say the method cannot be overwritten, the language does something that gives similar result.

  • 1

    Got it, now I’ve seen your edit. In Java the @Override annotation is optional, so I found it a little strange when I read about it. Thank you very much!

  • 2

    Yeah, Java does it override whether you like it or not.

  • 1

    Actually Java never does shadowing (or "Hiding" or "reintroduce") of an instance method; on the contrary, the Java always overrides it. So also "don’t want to override" in Java doesn’t make much sense. If Hiding is so important (and in my opinion it is completely expendable in a good design, as well as heritage itself is often also expendable), just use a language that supports. Finally, wanting even the behavior of shadowing in Java, in practice you will have it whenever in the child class you fail to invoke the parent class method.

  • @Caffé It is true, I got confused in the terms used. But the answer is not wrong. But it is not worth arguing with you. You like to negative because you have the wrong comma.

  • So I imagine you agree with my issue by removing the misinformation, so there’s no more reason to deny.

  • @Caffé is okay.

Show 3 more comments

4

When you use inheritance the class you receive automatically has the same methods and attributes.

In some cases you need to change the method of the class you are extending. The example below demonstrates this difference. The person has only two attributes, so to return the data I can return only name and Cpf. In the case of Employee besides name Cpf, it will be necessary to return the salary so it will be necessary to rewrite the method. Therefore we use "@Override" to indicate that in that class the "getDados" method must have a specific behavior.

class Pessoa {

    protected String nome;
    protected String cpf;

    public Pessoa(String nome, String cpf){
        this.nome = nome;
        this.cpf = cpf;
    }

    public String getCpf(){
        return cpf;
    }

    public void setCpf(String cpf){
        this.cpf = cpf
    }

    public String getNome(){
        return nome;
    }

    public void setNome(String nome){
        this.nome = nome;
    }

    public String getDados(){
        return cpf + "-" + nome;
    }
}

class Funcionario extends Pessoa /* Estende a classe Pessoa */{

    protected double salario;

    public Funcionario(String nome, String cpf, double salario){
        super(nome, cpf); /* Chama o método construtor da classe Pessoa */
        this.salario = salario;
    }

    public double getSalario(){
        return salario;
    }

    public void setSalario(double salario){
        this.salario = salario;
    }

    @Override /* Sobrescreve o método da classe pessoa, dessa forma irá rodar o método da classe Funcionário */
    public String getDados(){
        return cpf + "-" + nome + "-" + salario;
    }
}

class HelloWorld {
    public static void main(String[] args) {
        System.out.println(new Pessoa("Joao Maria", "987.456.777-45").getDados()); // Display the string.
        System.out.println(new Funcionario("Joao Carlos", "456.222.444-33", 1256.00).getDados());
    }
}

4

Extend

When you extend a class (abstract or not), you are causing the new class to have all the methods and attributes of the class you are extending.
If you extend the class below

class Animal{
    String raca;

    public String getRaca(){
        return raca;
    }
}

in a class called Gato, your new class will have the attribute raca and the method getRaca() already implemented.

Overwrite

But in your class Gato, you can override the method getRaca, causing it to have another behavior, or even to have some code added. See the example

class Gato extends Animal{
    public string getRaca(){
        return "Raça qualquer"; //Aqui eu estou sobrescrevendo o comportamento do método
    }
}

class Cachorro extends Animal{
    public String getRaca(){
        String base = super.getRaca(); //Aqui estou usando o método da "classe pai"
        return "Cachorro: " + base; //Aqui o retorno da classe filha
    }
}

3

Examples:

Extend:

class Pessoa {

    String nome;

    setNome(String nome) { this.nome = nome }
    getNome() { return this.nome }  
}

class Funcionario extends Pessoa {

    /* Método getPis() ou setPis(String pis) são novos métodos da 
     *  classe Funcionário sendo que a mesma é filha da classe Pessoa      
     */

    String pis;

    setPis(String pis){ this.pis = pis }
    getPis() { return this.pis }  
}

Overwrite:

class Pessoa {

    String nome;

    setNome(String nome) { this.nome = nome }
    getNome() { return this.nome }  
}

class Funcionario extends Pessoa {

    String pis;

    setPis(String pis){ this.pis = pis }
    getPis() { return this.pis } 

    /* Aqui estamos sobrescrevendo um método que existe na classe
     * pai da classe Pessoa passando um valor padrão para o atributo nome
     * diferente do método setNome da classe pai
     */ 

    @Override
    setNome(String nome) { this.nome = "Sou tratado de forma diferente" }
}

Browser other questions tagged

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