How to realize Polymorphism in Java object-oriented
This article mainly introduces the Java object-oriented how to achieve polymorphism, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Reproduced at: http://www.verejava.com/?id=16992843565554
/ * topic: children eat (apples, grapes, mangoes) ideas: 1. Abstract classes: Baby, Apple, Grape 2. Find out the class relationship: Apple, grape-> child 3. Find out the attributes: child (name, apple quote, grape reference) apple (name) grape (name) 4. Find out how: children eat (eat) apples or grapes * / public class Polymorphism2 {public static void main (String [] args) {/ / instantiate an Baby Baby baby = new Baby ("Li Ming"); / / instantiate an apple and a grape Apple apple = new Apple ("Red Fuji") Grape grape = new Grape ("black grape"); Mango mango = new Mango ("big mango"); / / Li Ming eats apples and grapes baby.eat (apple); System.out.println (baby.getName ()) + "happy to say I ate" + baby.getApple (). GetName (); baby.eat (grape) System.out.println (baby.getName () + "happily say I ate" + baby.getGrape (). GetName ()); baby.eat (mango); System.out.println (baby.getName () + "happily say I ate" + baby.getMango (). GetName ());}} class Baby {private Apple apple; private Grape grape; private Mango mango Private String name; public Baby (String name) {this.name = name;} public String getName () {return this.name;} public Apple getApple () {return this.apple;} public Grape getGrape () {return this.grape } public Mango getMango () {return this.mango;} / / eat Apple public void eat (Apple apple) {this.apple = apple;} / / eat Grape public void eat (Grape grape) {this.grape = grape } / / eat public void eat (Mango mango) {this.mango = mango;}} class Apple {private String name; public Apple (String name) {this.name = name;} public String getName () {return this.name;}} class Grape {private String name Public Grape (String name) {this.name = name;} public String getName () {return this.name;}} class Mango {private String name; public Mango (String name) {this.name = name;} public String getName () {return this.name }} Thank you for reading this article carefully. I hope the article "how to achieve Polymorphism in Java object orientation" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!