DEV Community

Jorge L, Morla
Jorge L, Morla

Posted on

3 3

Metodos Virtuales en Java

"Java virtual method" son metodos que una subclase hereda de una clase padre y que pasan a ser sobrescritos dandole un comportamiento polimorfo. Este proceso tambien es comunmente llamado sobreescritura de metodos.

Para que un metodo sea valido para ser sobreescrito no pueden ser de tipo staticos ni finales y como minimo deben tener protected como modificador de acceso.

Supongamos que tenemos la siguente Clase padre Mammal

public class Mammal {


    public void swim() {
        System.out.println("A mammal swimming");
    }
}

Enter fullscreen mode Exit fullscreen mode

Estas dos subclases Elephant y Hippo que heredan de Mammal y sobreescriben el metodo public void swim() de la misma.

public class Elephant extends Mammal {

    @Override
    public void swim() {
        System.out.println("An Elephant swiming");
    }
}

public class Hippo extends Mammal {


    @Override
    public void swim() {
        System.out.println("A hippo swiming");
    }
}
Enter fullscreen mode Exit fullscreen mode

Si ejecutamos el siguente ejemplo podemos ver como obtenemos resultados distintos llamando el mismo metodo de la clase Mammal cuando asignamos a la variable una nueva instancia de cada subtipo.

...
public static void main(String ...args) {


        Mammal mammal = new Elephant();
        mammal.swim();

        mammal = new Hippo();
        mammal.swim();

    }
Enter fullscreen mode Exit fullscreen mode

al final obtenemos.

An Elephant swiming
A hippo swiming
BUILD SUCCESSFUL (total time: 1 second)

Enter fullscreen mode Exit fullscreen mode

Gracias por tomarte el tiempo para leer. Saludos Cordiales :)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay