What is virtual method calling in java?

前端 未结 4 627
故里飘歌
故里飘歌 2020-12-01 13:05

Ive saw the next paragraph in some computer science test and i\'ll hope i can get here a good explanation of what it means because i googled it for an hour and can\'t find a

4条回答
  •  甜味超标
    2020-12-01 13:18

    Suppose you have a class Fruit, with two subclasses Orange and Banana. And suppose that Fruit has a String getColor() method.

    Orange can override the getColor() method to return "orange". Same for Banana, which can have it return "yellow".

    When some method uses an object of type Fruit, and call the getColor() method, the method that will be called is Banana.getColor() if the type of the Fruit is in fact Banana.

     private void printColor(Fruit f) {
         System.out.println(f.getColor());
     }
    
     ...
    
     Fruit fruit1 = new Banana();
     Fruit fruit2 = new Orange();
     printColor(fruit1); // prints yellow
     printColor(fruit2); // prints orange     
    

提交回复
热议问题