Polymorphism in Java

-1

When polymorphism is used can the methods be overwritten and is polymorphism still considered? for example: the parent class inherits a method from the daughter class and in the daughter class, I write that method to add an attribute of my daughter class. Is it still considered a polymorphism?

    
asked by Eduardo R 25.04.2018 в 20:05
source

2 answers

2

YES, it is still considered polymorphism, in fact that is why it is called polymorphism (because it acquires different forms)

For example, if you have a class called Animal of the form:

public class Animal{
    private int numeroPatas;
    private String nombre;

    public Animal(){
    }

    ....gettersAndSetters()....
}

And then you create the class PerroHerido that inherits from animal:

public class PerroHerido extends Animal{
    private int numeroPatas;
    private int numeroPatasHeridas;
    private String raza;

    public PerroHerido(){
        super();
    }

    @Override
    public void setNumeroPatas(int ptasHeridas, int ptasBuenas){ //este método ya está en la clase padre pero lo sobreescribimos
        this.numeroPatas = ptasBuenas;
        this.numeroPatasHeridas = ptasHeridas;
    }
}

In this way the animal class is still a parent of the PerroHerido class, but the daughter has altered one of the methods to define other properties or attributes of herself.

Even so it is still polymorphism, it changed shape in one of its daughters.

    
answered by 25.04.2018 в 22:03
1

Of course, yes, that's what polymorphism is about.

An inherited method can be overwritten to make its implementation more specific, and if you have several child classes such as Dog and Fish that inherit from Animal, you can declare an abstract method in the parent class called moverse() in which , will have a different behavior according to the instance to which the object belongs.

Example:

Animal miPerro = new Perro();
Animal miPez = new Pez();

miPerro.moverse();
miPez.moverse();

The previous methods will have different behaviors since they are polymorphic.

    
answered by 26.04.2018 в 03:08