Pregunta

En términos de Java, cuando alguien pregunta:

  

¿Qué es el polimorfismo?

¿Sería una sobrecarga o reemplazar una respuesta aceptable?

Creo que hay algo más que eso.

Si tenía una clase base abstracta que definía un método sin implementación, y definió ese método en la subclase, ¿eso sigue anulando?

Creo que la sobrecarga no es la respuesta correcta con seguridad.

¿Fue útil?

Solución

La forma más clara de expresar el polimorfismo es a través de una clase base (o interfaz) abstracta

public abstract class Human{
   ...
   public abstract void goPee();
}

Esta clase es abstracta porque el método goPee () no es definible para los Humanos. Solo es definible para las subclases Hombre y Mujer. Además, el humano es un concepto abstracto & # 8212; No puedes crear un humano que no sea Hombre ni Mujer. Debe ser uno u otro.

Por lo tanto, diferimos la implementación utilizando la clase abstracta.

public class Male extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Stand Up");
    }
}

y

public class Female extends Human{
...
    @Override
    public void goPee(){
        System.out.println("Sit Down");
    }
}

Ahora podemos decirle a una habitación llena de humanos que hagan pipí.

public static void main(String[] args){
    ArrayList<Human> group = new ArrayList<Human>();
    group.add(new Male());
    group.add(new Female());
    // ... add more...

    // tell the class to take a pee break
    for (Human person : group) person.goPee();
}

Ejecutar esto produciría:

Stand Up
Sit Down
...

Otros consejos

Polimorfismo es la capacidad de una instancia de clase de comportarse como si fuera una instancia de otra clase en su árbol de herencia, la mayoría de las veces una de sus clases ancestrales. Por ejemplo, en Java todas las clases heredan de Object. Por lo tanto, puede crear una variable de tipo Objeto y asignarle una instancia de cualquier clase.

Una anulación es un tipo de función que ocurre en una clase que hereda de otra clase. Una función de anulación " reemplaza " una función heredada de la clase base, pero lo hace de tal manera que se llama incluso cuando una instancia de su clase pretende ser un tipo diferente a través del polimorfismo. Refiriéndose al ejemplo anterior, puede definir su propia clase y anular la función toString (). Debido a que esta función se hereda de Objeto, aún estará disponible si copia una instancia de esta clase en una variable de tipo Objeto. Normalmente, si llama a toString () en su clase mientras pretende ser un Objeto, la versión de toString que realmente se activará es la definida en el propio Objeto. Sin embargo, debido a que la función es una anulación, la definición de toString () de su clase se usa incluso cuando el tipo verdadero de la instancia de la clase está oculto detrás del polimorfismo.

Sobrecarga es la acción de definir varios métodos con el mismo nombre, pero con diferentes parámetros. No tiene relación con la anulación o el polimorfismo.

Aquí hay un ejemplo de polimorfismo en pseudo-C # / Java:

class Animal
{
    abstract string MakeNoise ();
}

class Cat : Animal {
    string MakeNoise () {
        return "Meow";
    }
}

class Dog : Animal {
    string MakeNoise () {
        return "Bark";
    }
}

Main () {
   Animal animal = Zoo.GetAnimal ();
   Console.WriteLine (animal.MakeNoise ());
}

La función Principal no conoce el tipo del animal y depende del comportamiento de una implementación particular del método MakeNoise ().

Edit: Parece que Brian me dio una paliza. Es curioso que utilizamos el mismo ejemplo. Pero el código anterior debería ayudar a aclarar los conceptos.

Polimorfismo significa más de una forma, el mismo objeto realiza diferentes operaciones de acuerdo con el requisito.

El polimorfismo se puede lograr usando dos formas, esas son

  1. Anulación del método
  2. Sobrecarga del método

Sobrecarga de métodos significa escribir dos o más métodos en la misma clase usando el mismo nombre de método, pero los parámetros que pasan son diferentes.

Anulación del método significa que usamos los nombres de los métodos en las diferentes clases, lo que significa que el método de la clase principal se usa en la clase secundaria.

En Java para lograr el polimorfismo, una variable de referencia de superclase puede contener el objeto de subclase.

Para lograr el polimorfismo, todos los desarrolladores deben usar los mismos nombres de métodos en el proyecto.

Tanto la anulación como la sobrecarga se utilizan para lograr el polimorfismo.

Podrías tener un método en una clase     que se invalida en uno o     más subclases. El metodo hace     diferentes cosas dependiendo de la cual     La clase se usó para instanciar un objeto.

    abstract class Beverage {
       boolean isAcceptableTemperature();
    }

    class Coffee extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature > 70;
       }
    }

    class Wine extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature < 10;
       }
    }

También podrías tener un método que sea      sobrecargado con dos o más conjuntos de argumentos. El metodo hace     diferentes cosas basadas en la     tipo (s) de argumento (s) pasados.

    class Server {
        public void pour (Coffee liquid) {
            new Cup().fillToTopWith(liquid);
        }

        public void pour (Wine liquid) {
            new WineGlass().fillHalfwayWith(liquid);
        }

        public void pour (Lemonade liquid, boolean ice) {
            Glass glass = new Glass();
            if (ice) {
                glass.fillToTopWith(new Ice());
            }
            glass.fillToTopWith(liquid);
        }
    }

Tienes razón en que la sobrecarga no es la respuesta.

Ninguno de los dos está anulando. Anular es el medio por el cual se obtiene el polimorfismo. El polimorfismo es la capacidad de un objeto para variar el comportamiento en función de su tipo. Esto se demuestra mejor cuando el llamador de un objeto que exhibe polimorfismo no es consciente de qué tipo específico es el objeto.

Específicamente decir que la sobrecarga o la anulación no da la imagen completa. El polimorfismo es simplemente la capacidad de un objeto para especializar su comportamiento en función de su tipo.

No estaría de acuerdo con algunas de las respuestas aquí en que la sobrecarga es una forma de polimorfismo (polimorfismo paramétrico) en el caso de que un método con el mismo nombre pueda comportarse de manera diferente para diferentes tipos de parámetros. Un buen ejemplo es la sobrecarga del operador. Puede definir " + " para aceptar diferentes tipos de parámetros, digamos cadenas o int's, y basados ??en esos tipos, " + " se comportará de manera diferente.

El polimorfismo también incluye la herencia y los métodos de anulación, aunque pueden ser abstractos o virtuales en el tipo base. En términos de polimorfismo basado en la herencia, Java solo admite la herencia de una sola clase, lo que limita su comportamiento polimórfico al de una sola cadena de tipos básicos. Java admite la implementación de múltiples interfaces, que es otra forma de comportamiento polimórfico.

Polimorfismo simplemente significa " Muchas formas " ;.

No REQUIERE herencia para lograr ... ya que la implementación de la interfaz, que no es herencia en absoluto, satisface las necesidades polimórficas. Podría decirse que la implementación de la interfaz satisface las necesidades polimórficas " Mejor " que la herencia.

Por ejemplo, ¿crearías una súper clase para describir todas las cosas que pueden volar? Debería pensar que no. Sería mejor que te sirvieran para crear una interfaz que describa el vuelo y dejarlo así.

Entonces, dado que las interfaces describen el comportamiento y los nombres de los métodos describen el comportamiento (para el programador), no es demasiado difícil considerar la sobrecarga de métodos como una forma menor de polimorfismo.

El ejemplo clásico, los perros y los gatos son animales, los animales tienen el método makeNoise. Puedo recorrer una serie de animales que llaman makeNoise en ellos y esperar que hagan la implementación correspondiente.

El código de llamada no tiene que saber qué animal específico son.

Eso es lo que yo considero un polimorfismo.

El polimorfismo es la capacidad para que un objeto aparezca en múltiples formas. Esto implica el uso de funciones virtuales y de herencia para construir una familia de objetos que se pueden intercambiar. La clase base contiene los prototipos de las funciones virtuales, posiblemente no implementadas o con implementaciones predeterminadas según lo dicta la aplicación, y las diferentes clases derivadas las implementan de manera diferente para afectar diferentes comportamientos.

Ninguno:

La sobrecarga es cuando tienes el mismo nombre de función que toma diferentes parámetros.

La anulación se produce cuando una clase secundaria reemplaza el método de un padre por uno propio (esto en sí mismo no constituye polimorfismo).

El polimorfismo es un enlace tardío, por ej. los métodos de la clase base (padre) se llaman, pero no hasta que el tiempo de ejecución sepa la aplicación cuál es el objeto real; puede ser una clase hijo cuyos métodos son diferentes. Esto se debe a que se puede utilizar cualquier clase secundaria donde se define una clase base.

En Java ves mucho el polimorfismo con la biblioteca de colecciones:

int countStuff(List stuff) {
  return stuff.size();
}

La lista es la clase base, el compilador no tiene idea si está contando una lista vinculada, vector, matriz o una implementación de lista personalizada, siempre y cuando actúe como una Lista:

List myStuff = new MyTotallyAwesomeList();
int result = countStuff(myStuff);

Si estuvieras sobrecargando, tendrías:

int countStuff(LinkedList stuff) {...}
int countStuff(ArrayList stuff) {...}
int countStuff(MyTotallyAwesomeList stuff) {...}
etc...

y el compilador seleccionará la versión correcta de countStuff () para que coincida con los parámetros.

El término sobrecarga se refiere a tener varias versiones de algo con el mismo nombre, generalmente métodos con diferentes listas de parámetros

public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }

Por lo tanto, estas funciones pueden hacer lo mismo pero tiene la opción de llamarlo con una ID o un nombre. No tiene nada que ver con herencia, clases abstractas, etc.

La anulación generalmente se refiere al polimorfismo, como describió en su pregunta

la sobrecarga es cuando se definen 2 métodos con el mismo nombre pero con diferentes parámetros

la invalidación es cuando cambia el comportamiento de la clase base a través de una función con el mismo nombre en una subclase.

Por lo tanto, el polimorfismo está relacionado con la anulación, pero no la sobrecarga realmente.

Sin embargo, si alguien me dio una respuesta simple de " anular " para la pregunta "¿Qué es el polimorfismo?" Pediría una explicación más detallada.

anular es más como esconder un método heredado al declarar un método con el mismo nombre y firma que el método de nivel superior (súper método), esto agrega un comportamiento polimórfico a la clase. en otras palabras, la decisión de elegir el método de nivel a llamar se tomará en tiempo de ejecución y no en tiempo de compilación. esto lleva al concepto de interfaz e implementación.

  

¿Qué es el polimorfismo?

Desde java tutorial

La definición del diccionario de polimorfismo se refiere a un principio en biología en el que un organismo o especie puede tener muchas formas o etapas diferentes. Este principio también puede aplicarse a la programación orientada a objetos y lenguajes como el lenguaje Java. Las subclases de una clase pueden definir sus propios comportamientos únicos y, sin embargo, compartir algunas de las mismas funciones de la clase principal.

Al considerar los ejemplos y la definición, se debe aceptar overriding .

Con respecto a su segunda consulta:

  

Si tenía una clase base abstracta que definía un método sin implementación, y definió ese método en la subclase, ¿eso sigue anulando?

Debería llamarse anulación.

Eche un vistazo a este ejemplo para comprender los diferentes tipos de anulación.

  1. La clase base no proporciona implementación y la subclase debe anular el método completo - (resumen)
  2. La clase base proporciona una implementación predeterminada y la subclase puede cambiar el comportamiento
  3. La subclase agrega una extensión a la implementación de la clase base al llamar a super.methodName () como primera declaración
  4. La clase base define la estructura del algoritmo (método de plantilla) y la subclase anulará una parte del algoritmo

fragmento de código:

import java.util.HashMap;

abstract class Game implements Runnable{

    protected boolean runGame = true;
    protected Player player1 = null;
    protected Player player2 = null;
    protected Player currentPlayer = null;

    public Game(){
        player1 = new Player("Player 1");
        player2 = new Player("Player 2");
        currentPlayer = player1;
        initializeGame();
    }

    /* Type 1: Let subclass define own implementation. Base class defines abstract method to force
        sub-classes to define implementation    
    */

    protected abstract void initializeGame();

    /* Type 2: Sub-class can change the behaviour. If not, base class behaviour is applicable */
    protected void logTimeBetweenMoves(Player player){
        System.out.println("Base class: Move Duration: player.PlayerActTime - player.MoveShownTime");
    }

    /* Type 3: Base class provides implementation. Sub-class can enhance base class implementation by calling
        super.methodName() in first line of the child class method and specific implementation later */
    protected void logGameStatistics(){
        System.out.println("Base class: logGameStatistics:");
    }
    /* Type 4: Template method: Structure of base class can't be changed but sub-class can some part of behaviour */
    protected void runGame() throws Exception{
        System.out.println("Base class: Defining the flow for Game:");  
        while ( runGame) {
            /*
            1. Set current player
            2. Get Player Move
            */
            validatePlayerMove(currentPlayer);  
            logTimeBetweenMoves(currentPlayer);
            Thread.sleep(500);
            setNextPlayer();
        }
        logGameStatistics();
    }
    /* sub-part of the template method, which define child class behaviour */
    protected abstract void validatePlayerMove(Player p);

    protected void setRunGame(boolean status){
        this.runGame = status;
    }
    public void setCurrentPlayer(Player p){
        this.currentPlayer = p;
    }
    public void setNextPlayer(){
        if ( currentPlayer == player1) {
            currentPlayer = player2;
        }else{
            currentPlayer = player1;
        }
    }
    public void run(){
        try{
            runGame();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

class Player{
    String name;
    Player(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

/* Concrete Game implementation  */
class Chess extends Game{
    public Chess(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized Chess game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate Chess move:"+p.getName());
    }
    protected void logGameStatistics(){
        super.logGameStatistics();
        System.out.println("Child class: Add Chess specific logGameStatistics:");
    }
}
class TicTacToe extends Game{
    public TicTacToe(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized TicTacToe game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate TicTacToe move:"+p.getName());
    }
}

public class Polymorphism{
    public static void main(String args[]){
        try{

            Game game = new Chess();
            Thread t1 = new Thread(game);
            t1.start();
            Thread.sleep(1000);
            game.setRunGame(false);
            Thread.sleep(1000);

            game = new TicTacToe();
            Thread t2 = new Thread(game);
            t2.start();
            Thread.sleep(1000);
            game.setRunGame(false);

        }catch(Exception err){
            err.printStackTrace();
        }       
    }
}

salida:

Child class: Initialized Chess game
Base class: Defining the flow for Game:
Child class: Validate Chess move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate Chess move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:
Child class: Add Chess specific logGameStatistics:
Child class: Initialized TicTacToe game
Base class: Defining the flow for Game:
Child class: Validate TicTacToe move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate TicTacToe move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:

Creo que ustedes están mezclando conceptos. Polimorfismo es la capacidad de un objeto para comportarse de manera diferente en el tiempo de ejecución. Para lograr esto, necesitas dos requisitos:

  1. Encuadernación tardía
  2. Herencia.

Habiendo dicho que sobrecargar significa algo diferente a anular dependiendo del idioma que estés usando. Por ejemplo, en Java no existe anulando sino sobrecargando . Los métodos Sobrecargados con una firma diferente a su clase base están disponibles en la subclase. De lo contrario, se anularían (por favor, ver que me refiero a que ahora no hay forma de llamar a su método de clase base desde fuera del objeto).

Sin embargo, en C ++ eso no es así. Cualquier método sobrecargado , independientemente de si la firma es la misma o no (cantidad diferente, tipo diferente) también se reemplaza . Es decir, el método de la clase base ya no está disponible en la subclase cuando se llama desde fuera del objeto de la subclase, obviamente.

Entonces la respuesta es cuando se habla de Java, use sobrecarga . En cualquier otro idioma puede ser diferente como sucede en c ++

Although, Polymorphism is already explained in great details in this post but I would like put more emphasis on why part of it.

Why Polymorphism is so important in any OOP language.

Let’s try to build a simple application for a TV with and without Inheritance/Polymorphism. Post each version of the application, we do a small retrospective.

Supposing, you are a software engineer at a TV company and you are asked to write software for Volume, Brightness and Colour controllers to increase and decrease their values on user command.

You start with writing classes for each of these features by adding

  1. set:- To set a value of a controller.(Supposing this has controller specific code)
  2. get:- To get a value of a controller.(Supposing this has controller specific code)
  3. adjust:- To validate the input and setting a controller.(Generic validations.. independent of controllers)
  4. user input mapping with controllers :- To get user input and invoking controllers accordingly.

Application Version 1

import java.util.Scanner;    
class VolumeControllerV1 {
    private int value;
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of VolumeController \t"+this.value);
        this.value = value;
        System.out.println("New value of VolumeController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}
class  BrightnessControllerV1 {
    private int value;
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of BrightnessController \t"+this.value);
        this.value = value;
        System.out.println("New value of BrightnessController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}
class ColourControllerV1    {
    private int value;
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of ColourController \t"+this.value);
        this.value = value;
        System.out.println("New value of ColourController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}

/*
 *       There can be n number of controllers
 * */
public class TvApplicationV1 {
    public static void main(String[] args)  {
        VolumeControllerV1 volumeControllerV1 = new VolumeControllerV1();
        BrightnessControllerV1 brightnessControllerV1 = new BrightnessControllerV1();
        ColourControllerV1 colourControllerV1 = new ColourControllerV1();


        OUTER: while(true) {
            Scanner sc=new Scanner(System.in);
            System.out.println(" Enter your option \n Press 1 to increase volume \n Press 2 to decrease volume");
            System.out.println(" Press 3 to increase brightness \n Press 4 to decrease brightness");
            System.out.println(" Press 5 to increase color \n Press 6 to decrease color");
            System.out.println("Press any other Button to shutdown");
            int button = sc.nextInt();
            switch (button) {
                case  1:    {
                    volumeControllerV1.adjust(5);
                    break;
                }
                case 2: {
                    volumeControllerV1.adjust(-5);
                    break;
                }
                case  3:    {
                    brightnessControllerV1.adjust(5);
                    break;
                }
                case 4: {
                    brightnessControllerV1.adjust(-5);
                    break;
                }
                case  5:    {
                    colourControllerV1.adjust(5);
                    break;
                }
                case 6: {
                colourControllerV1.adjust(-5);
                break;
            }
            default:
                System.out.println("Shutting down...........");
                break OUTER;
        }

    }
    }
}

Now you have our first version of working application ready to be deployed. Time to analyze the work done so far.

Issues in TV Application Version 1

  1. Adjust(int value) code is duplicate in all three classes. You would like to minimize the code duplicity. (But you did not think of common code and moving it to some super class to avoid duplicate code)

You decide to live with that as long as your application works as expected.

After sometimes, your Boss comes back to you and asks you to add reset functionality to the existing application. Reset would set all 3 three controller to their respective default values.

You start writing a new class (ResetFunctionV2) for the new functionality and map the user input mapping code for this new feature.

Application Version 2

import java.util.Scanner;
class VolumeControllerV2    {

    private int defaultValue = 25;
    private int value;

    int getDefaultValue() {
        return defaultValue;
    }
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of VolumeController \t"+this.value);
        this.value = value;
        System.out.println("New value of VolumeController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}
class  BrightnessControllerV2   {

    private int defaultValue = 50;
    private int value;
    int get()    {
        return value;
    }
    int getDefaultValue() {
        return defaultValue;
    }
    void set(int value) {
        System.out.println("Old value of BrightnessController \t"+this.value);
        this.value = value;
        System.out.println("New value of BrightnessController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}
class ColourControllerV2    {

    private int defaultValue = 40;
    private int value;
    int get()    {
        return value;
    }
    int getDefaultValue() {
        return defaultValue;
    }
    void set(int value) {
        System.out.println("Old value of ColourController \t"+this.value);
        this.value = value;
        System.out.println("New value of ColourController \t"+this.value);
    }
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}

class ResetFunctionV2 {

    private VolumeControllerV2 volumeControllerV2 ;
    private BrightnessControllerV2 brightnessControllerV2;
    private ColourControllerV2 colourControllerV2;

    ResetFunctionV2(VolumeControllerV2 volumeControllerV2, BrightnessControllerV2 brightnessControllerV2, ColourControllerV2 colourControllerV2)  {
        this.volumeControllerV2 = volumeControllerV2;
        this.brightnessControllerV2 = brightnessControllerV2;
        this.colourControllerV2 = colourControllerV2;
    }
    void onReset()    {
        volumeControllerV2.set(volumeControllerV2.getDefaultValue());
        brightnessControllerV2.set(brightnessControllerV2.getDefaultValue());
        colourControllerV2.set(colourControllerV2.getDefaultValue());
    }
}
/*
 *       so on
 *       There can be n number of controllers
 *
 * */
public class TvApplicationV2 {
    public static void main(String[] args)  {
        VolumeControllerV2 volumeControllerV2 = new VolumeControllerV2();
        BrightnessControllerV2 brightnessControllerV2 = new BrightnessControllerV2();
        ColourControllerV2 colourControllerV2 = new ColourControllerV2();

        ResetFunctionV2 resetFunctionV2 = new ResetFunctionV2(volumeControllerV2, brightnessControllerV2, colourControllerV2);

        OUTER: while(true) {
            Scanner sc=new Scanner(System.in);
            System.out.println(" Enter your option \n Press 1 to increase volume \n Press 2 to decrease volume");
            System.out.println(" Press 3 to increase brightness \n Press 4 to decrease brightness");
            System.out.println(" Press 5 to increase color \n Press 6 to decrease color");
            System.out.println(" Press 7 to reset TV \n Press any other Button to shutdown");
            int button = sc.nextInt();
            switch (button) {
                case  1:    {
                    volumeControllerV2.adjust(5);
                    break;
                }
                case 2: {
                    volumeControllerV2.adjust(-5);
                    break;
                }
                case  3:    {
                    brightnessControllerV2.adjust(5);
                    break;
                }
                case 4: {
                    brightnessControllerV2.adjust(-5);
                    break;
                }
                case  5:    {
                    colourControllerV2.adjust(5);
                    break;
                }
                case 6: {
                    colourControllerV2.adjust(-5);
                    break;
                }
                case 7: {
                    resetFunctionV2.onReset();
                    break;
                }
                default:
                    System.out.println("Shutting down...........");
                    break OUTER;
            }

        }
    }
}

So you have your application ready with Reset feature. But, now you start realizing that

Issues in TV Application Version 2

  1. If a new controller is introduced to the product, you have to change Reset feature code.
  2. If the count of the controller grows very high, you would have issue in holding the references of the controllers.
  3. Reset feature code is tightly coupled with all the controllers Class’s code(to get and set default values).
  4. Reset feature class (ResetFunctionV2) can access other method of the Controller class’s (adjust) which is undesirable.

At the same time, You hear from you Boss that you might have to add a feature wherein each of controllers, on start-up, needs to check for the latest version of driver from company’s hosted driver repository via internet.

Now you start thinking that this new feature to be added resembles with Reset feature and Issues of Application (V2) will be multiplied if you don’t re-factor your application.

You start thinking of using inheritance so that you can take advantage from polymorphic ability of JAVA and you add a new abstract class (ControllerV3) to

  1. Declare the signature of get and set method.
  2. Contain adjust method implementation which was earlier replicated among all the controllers.
  3. Declare setDefault method so that reset feature can be easily implemented leveraging Polymorphism.

With these improvements, you have version 3 of your TV application ready with you.

Application Version 3

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

abstract class ControllerV3 {
    abstract void set(int value);
    abstract int get();
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
    abstract void setDefault();
}
class VolumeControllerV3 extends ControllerV3   {

    private int defaultValue = 25;
    private int value;

    public void setDefault() {
        set(defaultValue);
    }
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of VolumeController \t"+this.value);
        this.value = value;
        System.out.println("New value of VolumeController \t"+this.value);
    }
}
class  BrightnessControllerV3  extends ControllerV3   {

    private int defaultValue = 50;
    private int value;

    public void setDefault() {
        set(defaultValue);
    }
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of BrightnessController \t"+this.value);
        this.value = value;
        System.out.println("New value of BrightnessController \t"+this.value);
    }
}
class ColourControllerV3 extends ControllerV3   {

    private int defaultValue = 40;
    private int value;

    public void setDefault() {
        set(defaultValue);
    }
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of ColourController \t"+this.value);
        this.value = value;
        System.out.println("New value of ColourController \t"+this.value);
    }
}

class ResetFunctionV3 {

    private List<ControllerV3> controllers = null;

    ResetFunctionV3(List<ControllerV3> controllers)  {
        this.controllers = controllers;
    }
    void onReset()    {
        for (ControllerV3 controllerV3 :this.controllers)  {
            controllerV3.setDefault();
        }
    }
}
/*
 *       so on
 *       There can be n number of controllers
 *
 * */
public class TvApplicationV3 {
    public static void main(String[] args)  {
        VolumeControllerV3 volumeControllerV3 = new VolumeControllerV3();
        BrightnessControllerV3 brightnessControllerV3 = new BrightnessControllerV3();
        ColourControllerV3 colourControllerV3 = new ColourControllerV3();

        List<ControllerV3> controllerV3s = new ArrayList<>();
        controllerV3s.add(volumeControllerV3);
        controllerV3s.add(brightnessControllerV3);
        controllerV3s.add(colourControllerV3);

        ResetFunctionV3 resetFunctionV3 = new ResetFunctionV3(controllerV3s);

        OUTER: while(true) {
            Scanner sc=new Scanner(System.in);
            System.out.println(" Enter your option \n Press 1 to increase volume \n Press 2 to decrease volume");
            System.out.println(" Press 3 to increase brightness \n Press 4 to decrease brightness");
            System.out.println(" Press 5 to increase color \n Press 6 to decrease color");
            System.out.println(" Press 7 to reset TV \n Press any other Button to shutdown");
            int button = sc.nextInt();
            switch (button) {
                case  1:    {
                    volumeControllerV3.adjust(5);
                    break;
                }
                case 2: {
                    volumeControllerV3.adjust(-5);
                    break;
                }
                case  3:    {
                    brightnessControllerV3.adjust(5);
                    break;
                }
                case 4: {
                    brightnessControllerV3.adjust(-5);
                    break;
                }
                case  5:    {
                    colourControllerV3.adjust(5);
                    break;
                }
                case 6: {
                    colourControllerV3.adjust(-5);
                    break;
                }
                case 7: {
                    resetFunctionV3.onReset();
                    break;
                }
                default:
                    System.out.println("Shutting down...........");
                    break OUTER;
            }

        }
    }
}

Although most of the Issue listed in issue list of V2 were addressed except

Issues in TV Application Version 3

  1. Reset feature class (ResetFunctionV3) can access other method of the Controller class’s (adjust) which is undesirable.

Again, you think of solving this problem, as now you have another feature (driver update at startup) to implement as well. If you don’t fix it, it will get replicated to new features as well.

So you divide the contract defined in abstract class and write 2 interfaces for

  1. Reset feature.
  2. Driver Update.

And have your 1st concrete class implement them as below

Application Version 4

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

interface OnReset {
    void setDefault();
}
interface OnStart {
    void checkForDriverUpdate();
}
abstract class ControllerV4 implements OnReset,OnStart {
    abstract void set(int value);
    abstract int get();
    void adjust(int value)  {
        int temp = this.get();
        if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0)))    {
            System.out.println("Can not adjust any further");
            return;
        }
        this.set(temp + value);
    }
}

class VolumeControllerV4 extends ControllerV4 {

    private int defaultValue = 25;
    private int value;
    @Override
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of VolumeController \t"+this.value);
        this.value = value;
        System.out.println("New value of VolumeController \t"+this.value);
    }
    @Override
    public void setDefault() {
        set(defaultValue);
    }

    @Override
    public void checkForDriverUpdate()    {
        System.out.println("Checking driver update for VolumeController .... Done");
    }
}
class  BrightnessControllerV4 extends ControllerV4 {

    private int defaultValue = 50;
    private int value;
    @Override
    int get()    {
        return value;
    }
    @Override
    void set(int value) {
        System.out.println("Old value of BrightnessController \t"+this.value);
        this.value = value;
        System.out.println("New value of BrightnessController \t"+this.value);
    }

    @Override
    public void setDefault() {
        set(defaultValue);
    }

    @Override
    public void checkForDriverUpdate()    {
        System.out.println("Checking driver update for BrightnessController .... Done");
    }
}
class ColourControllerV4 extends ControllerV4 {

    private int defaultValue = 40;
    private int value;
    @Override
    int get()    {
        return value;
    }
    void set(int value) {
        System.out.println("Old value of ColourController \t"+this.value);
        this.value = value;
        System.out.println("New value of ColourController \t"+this.value);
    }
    @Override
    public void setDefault() {
        set(defaultValue);
    }

    @Override
    public void checkForDriverUpdate()    {
        System.out.println("Checking driver update for ColourController .... Done");
    }
}
class ResetFunctionV4 {

    private List<OnReset> controllers = null;

    ResetFunctionV4(List<OnReset> controllers)  {
        this.controllers = controllers;
    }
    void onReset()    {
        for (OnReset onreset :this.controllers)  {
            onreset.setDefault();
        }
    }
}
class InitializeDeviceV4 {

    private List<OnStart> controllers = null;

    InitializeDeviceV4(List<OnStart> controllers)  {
        this.controllers = controllers;
    }
    void initialize()    {
        for (OnStart onStart :this.controllers)  {
            onStart.checkForDriverUpdate();
        }
    }
}
/*
*       so on
*       There can be n number of controllers
*
* */
public class TvApplicationV4 {
    public static void main(String[] args)  {
        VolumeControllerV4 volumeControllerV4 = new VolumeControllerV4();
        BrightnessControllerV4 brightnessControllerV4 = new BrightnessControllerV4();
        ColourControllerV4 colourControllerV4 = new ColourControllerV4();
        List<ControllerV4> controllerV4s = new ArrayList<>();
        controllerV4s.add(brightnessControllerV4);
        controllerV4s.add(volumeControllerV4);
        controllerV4s.add(colourControllerV4);

        List<OnStart> controllersToInitialize = new ArrayList<>();
        controllersToInitialize.addAll(controllerV4s);
        InitializeDeviceV4 initializeDeviceV4 = new InitializeDeviceV4(controllersToInitialize);
        initializeDeviceV4.initialize();

        List<OnReset> controllersToReset = new ArrayList<>();
        controllersToReset.addAll(controllerV4s);
        ResetFunctionV4 resetFunctionV4 = new ResetFunctionV4(controllersToReset);

        OUTER: while(true) {
            Scanner sc=new Scanner(System.in);
            System.out.println(" Enter your option \n Press 1 to increase volume \n Press 2 to decrease volume");
            System.out.println(" Press 3 to increase brightness \n Press 4 to decrease brightness");
            System.out.println(" Press 5 to increase color \n Press 6 to decrease color");
            System.out.println(" Press 7 to reset TV \n Press any other Button to shutdown");
            int button = sc.nextInt();
            switch (button) {
                case  1:    {
                    volumeControllerV4.adjust(5);
                    break;
                }
                case 2: {
                    volumeControllerV4.adjust(-5);
                    break;
                }
                case  3:    {
                    brightnessControllerV4.adjust(5);
                    break;
                }
                case 4: {
                    brightnessControllerV4.adjust(-5);
                    break;
                }
                case  5:    {
                    colourControllerV4.adjust(5);
                    break;
                }
                case 6: {
                    colourControllerV4.adjust(-5);
                    break;
                }
                case 7: {
                    resetFunctionV4.onReset();
                    break;
                }
                default:
                    System.out.println("Shutting down...........");
                    break OUTER;
            }

        }
    }
}

Now all of the issue faced by you got addressed and you realized that with the use of Inheritance and Polymorphism you could

  1. Keep various part of application loosely coupled.( Reset or Driver Update feature components don’t need to be made aware of actual controller classes(Volume, Brightness and Colour), any class implementing OnReset or OnStart will be acceptable to Reset or Driver Update feature components respectively).
  2. Application enhancement becomes easier.(New addition of controller wont impact reset or driver update feature component, and it is now really easy for you to add new ones)
  3. Keep layer of abstraction.(Now Reset feature can see only setDefault method of controllers and Reset feature can see only checkForDriverUpdate method of controllers)

Hope, this helps :-)

Polymorphism is more likely as far as it's meaning is concerned ... to OVERRIDING in java

It's all about different behavior of the SAME object in different situations(In programming way ... you can call different ARGUMENTS)

I think the example below will help you to understand ... Though it's not PURE java code ...

     public void See(Friend)
     {
        System.out.println("Talk");
     }

But if we change the ARGUMENT ... the BEHAVIOR will be changed ...

     public void See(Enemy)
     {
        System.out.println("Run");
     }

The Person(here the "Object") is same ...

Polymorphism is a multiple implementations of an object or you could say multiple forms of an object. lets say you have class Animals as the abstract base class and it has a method called movement() which defines the way that the animal moves. Now in reality we have different kinds of animals and they move differently as well some of them with 2 legs, others with 4 and some with no legs, etc.. To define different movement() of each animal on earth, we need to apply polymorphism. However, you need to define more classes i.e. class Dogs Cats Fish etc. Then you need to extend those classes from the base class Animals and override its method movement() with a new movement functionality based on each animal you have. You can also use Interfaces to achieve that. The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods "with same name" but with different parameters on same object or class.

Polymorphism relates to the ability of a language to have different object treated uniformly by using a single interfaces; as such it is related to overriding, so the interface (or the base class) is polymorphic, the implementor is the object which overrides (two faces of the same medal)

anyway, the difference between the two terms is better explained using other languages, such as c++: a polymorphic object in c++ behaves as the java counterpart if the base function is virtual, but if the method is not virtual the code jump is resolved statically, and the true type not checked at runtime so, polymorphism include the ability for an object to behave differently depending on the interface used to access it; let me make an example in pseudocode:

class animal {
    public void makeRumor(){
        print("thump");
    }
}
class dog extends animal {
    public void makeRumor(){
        print("woff");
    }
}

animal a = new dog();
dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

(supposing that makeRumor is NOT virtual)

java doesn't truly offer this level of polymorphism (called also object slicing).

animal a = new dog(); dog b = new dog();

a.makeRumor() -> prints thump
b.makeRumor() -> prints woff

on both case it will only print woff.. since a and b is refering to class dog

import java.io.IOException;

class Super {

    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName() + " - I'm parent");
        return null;
    }

}

class SubOne extends Super {

    @Override
    protected Super getClassName(Super s)  {
        System.out.println(this.getClass().getSimpleName() + " - I'm Perfect Overriding");
        return null;
    }

}

class SubTwo extends Super {

    @Override
    protected Super getClassName(Super s) throws NullPointerException {
        System.out.println(this.getClass().getSimpleName() + " - I'm Overriding and Throwing Runtime Exception");
        return null;
    }

}

class SubThree extends Super {

    @Override
    protected SubThree getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Returning SubClass Type");
        return null;
    }

}

class SubFour extends Super {

    @Override
    protected Super getClassName(Super s) throws IOException {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Throwing Narrower Exception ");
        return null;
    }

}

class SubFive extends Super {

    @Override
    public Super getClassName(Super s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and have broader Access ");
        return null;
    }

}

class SubSix extends Super {

    public Super getClassName(Super s, String ol) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading ");
        return null;
    }

}

class SubSeven extends Super {

    public Super getClassName(SubSeven s) {
        System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading because Method signature (Argument) changed.");
        return null;
    }

}

public class Test{

    public static void main(String[] args) throws Exception {

        System.out.println("Overriding\n");

        Super s1 = new SubOne(); s1.getClassName(null);

        Super s2 = new SubTwo(); s2.getClassName(null);

        Super s3 = new SubThree(); s3.getClassName(null);

        Super s4 = new SubFour(); s4.getClassName(null);

        Super s5 = new SubFive(); s5.getClassName(null);

        System.out.println("Overloading\n");

        SubSix s6 = new SubSix(); s6.getClassName(null, null);

        s6 = new SubSix(); s6.getClassName(null);

        SubSeven s7 = new SubSeven(); s7.getClassName(s7);

        s7 = new SubSeven(); s7.getClassName(new Super());

    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top