Bookmark Topic Watch Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator


To learn more about polymorphism, mosey over to the campfire to hear about How my Dog learned Polymorphism

This is an application, not an applet. Here is a UML class diagram to show what classes we will be working with:



We have an interface called "Shape". The classes Circle, Box and Poly (short for polygon) all implement the Shape interface. That means that they have agreed to implement all of the methods in Shape.

Here is the complete source code for Shape.java:



Here is the source for our three classes:












And to show off polymorphism in action, here is a program that creates a bunch of Circle, Box and Poly objects and stores them in a Shape array. Then it goes through the array and draws all of the shapes.

Go ahead and copy these programs to your disk as Shape.java, Cirle.java, Box.java, Poly.java and ShowShapes.java. Compile 'em up and run ShowShapes. You should see the beginnings of how most modern graphical operating systems work.

Here's ShowShapes.java:



Note that to stop the program, you'll need to pull up the console you started it in and press control-C.


CodeBarnBeginnerJava
 
Get off me! Here, read this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
    Bookmark Topic Watch Topic
  • New Topic