Polymorphism vs Overriding vs Overloading

前端 未结 21 2813
北恋
北恋 2020-11-22 01:10

In terms of Java, when someone asks:

what is polymorphism?

Would overloading or overriding be

相关标签:
21条回答
  • 2020-11-22 01:20

    overriding is more like hiding an inherited method by declaring a method with the same name and signature as the upper level method (super method), this adds a polymorphic behaviour to the class . in other words the decision to choose wich level method to be called will be made at run time not on compile time . this leads to the concept of interface and implementation .

    0 讨论(0)
  • 2020-11-22 01:21

    Polymorphism is the ability for an object to appear in multiple forms. This involves using inheritance and virtual functions to build a family of objects which can be interchanged. The base class contains the prototypes of the virtual functions, possibly unimplemented or with default implementations as the application dictates, and the various derived classes each implements them differently to affect different behaviors.

    0 讨论(0)
  • 2020-11-22 01:24

    what is polymorphism?

    From java tutorial

    The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

    By considering the examples and definition, overriding should be accepted answer.

    Regarding your second query:

    IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

    It should be called overriding.

    Have a look at this example to understand different types of overriding.

    1. Base class provides no implementation and sub-class has to override complete method - (abstract)
    2. Base class provides default implementation and sub-class can change the behaviour
    3. Sub-class adds extension to base class implementation by calling super.methodName() as first statement
    4. Base class defines structure of the algorithm (Template method) and sub-class will override a part of algorithm

    code snippet:

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

    output:

    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:
    
    0 讨论(0)
  • 2020-11-22 01:25

    The clearest way to express polymorphism is via an abstract base class (or interface)

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

    This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other.

    So we defer the implementation by using the abstract class.

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

    and

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

    Now we can tell an entire room full of Humans to go pee.

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

    Running this would yield:

    Stand Up
    Sit Down
    ...
    
    0 讨论(0)
  • 2020-11-22 01:26

    Polymorphism simply means "Many Forms".

    It does not REQUIRE inheritance to achieve...as interface implementation, which is not inheritance at all, serves polymorphic needs. Arguably, interface implementation serves polymorphic needs "Better" than inheritance.

    For example, would you create a super-class to describe all things that can fly? I should think not. You would be be best served to create an interface that describes flight and leave it at that.

    So, since interfaces describe behavior, and method names describe behavior (to the programmer), it is not too far of a stretch to consider method overloading as a lesser form of polymorphism.

    0 讨论(0)
  • 2020-11-22 01:27

    The classic example, Dogs and cats are animals, animals have the method makeNoise. I can iterate through an array of animals calling makeNoise on them and expect that they would do there respective implementation.

    The calling code does not have to know what specific animal they are.

    Thats what I think of as polymorphism.

    0 讨论(0)
提交回复
热议问题