-
Polymorphism Help
Hi, I have looked and looked through the different definitions / explanations of polymorphism and I still don't understand it. So, from what I have came up with about it, I have made some code and was hoping that someone could tell me if this is polymorphism and if it is then please tell me what makes polymorphism. Thanks.
Code:
public class PlayWnd extends javax.swing.JPanel {
public int iIndex=0;
int gameStatus = -1;
int iLevel = 1;
Player cPlayer;
Player cBoss;
public int getGameStatus()
{
return gameStatus; //returns the gameStatus
}
/** Creates new form PlayWnd */
public PlayWnd(int iIndex) {
initComponents();
cPlayer = new Player(iIndex, jLblPlayer, jLblPH, jLblPP); //creates a new player
cBoss = new Player(3, jLblBoss, jLblBH, jLblBP); //creates a new boss
StartRound(); //executes StartRound
}
public void StartRound()
{
cPlayer.setHitPoint(cPlayer.iFullHitPoint); //sets the players hit points to 100
cPlayer.SetEnemy(cBoss); //sets the correct boss for the correct level
if (iLevel==1) //if it's level 1 then set the bosses health points to 100
cBoss.iFullHitPoint=100;
else if(iLevel==2) //if it's level 2 then set the bosses health points to 110
cBoss.iFullHitPoint=110;
else //if it's any other level then set the bosses health points to 125
cBoss.iFullHitPoint=125;
cBoss.setHitPoint(cBoss.iFullHitPoint); //sets the regular amount of hitpoints to 100
cBoss.SetEnemy(cPlayer); //sets the character that you chose
if (iLevel<3) //if the level is under 3 then it displays the level in text
jLblLevel.setText("Level " + iLevel);
else //if the level is equal to 3 or more then it sets the text to final level
jLblLevel.setText("Final Level");
cBoss.setIndex(iLevel + 2); //final level sets the index to + 2
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLblPlayer = new javax.swing.JLabel();
jLblBoss = new javax.swing.JLabel();
jLblLevel = new javax.swing.JLabel();
jLblVS = new javax.swing.JLabel();
jLblPH = new javax.swing.JLabel();
jLblPP = new javax.swing.JLabel();
jLblBP = new javax.swing.JLabel();
jLblBH = new javax.swing.JLabel();
jbtnAttack = new javax.swing.JButton();
jLblPlayer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/karate/HulkHogan.jpg"))); // NOI18N
jLblBoss.setIcon(new javax.swing.ImageIcon(getClass().getResource("/karate/Darth.jpg"))); // NOI18N
jLblLevel.setFont(new java.awt.Font("Tahoma", 1, 30)); // NOI18N
jLblLevel.setForeground(new java.awt.Color(255, 0, 0));
jLblLevel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLblLevel.setText("Level 1");
jLblLevel.setAlignmentX(0.5F);
jLblLevel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLblLevel.setRequestFocusEnabled(false);
jLblVS.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N
jLblVS.setForeground(new java.awt.Color(255, 0, 0));
jLblVS.setText("V.S");
jLblPH.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLblPH.setText("Hit Point: 100");
jLblPP.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLblPP.setText("Power: 10");
jLblBP.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLblBP.setText("Power: 10");
jLblBH.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLblBH.setText("Hit Point: 100");
jbtnAttack.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jbtnAttack.setText("Attack");
jbtnAttack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtnAttackActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLblPlayer)
.addGap(49, 49, 49)
.addComponent(jLblVS))
.addComponent(jLblPP)
.addGroup(layout.createSequentialGroup()
.addComponent(jLblPH)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
.addComponent(jLblLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLblBoss)
.addComponent(jLblBP)
.addComponent(jLblBH))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jbtnAttack, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(208, 208, 208))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLblPH)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLblPP))
.addGroup(layout.createSequentialGroup()
.addComponent(jLblBH)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLblBP))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLblLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLblBoss)
.addComponent(jLblPlayer))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
.addComponent(jLblVS)
.addGap(70, 70, 70)))
.addComponent(jbtnAttack)
.addContainerGap())
);
}// </editor-fold>
private void jbtnAttackActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
cPlayer.Attack(); //makes you attack your opponent
if (cBoss.getHitPoint()==0) //if the bosses health equals 0
{
if (iLevel==3) //if it's level 3 then the gameStatus is 2
gameStatus=2;
else //else, the gameStatus is 0
gameStatus=0;
CardLayout cl = (CardLayout)(this.getParent().getLayout()); //lets you switch panels
cl.show(this.getParent(), "MsgWnd"); //sets the panel to MsgWnd
MainWnd.cMsg.Init(); //displays the MsgWnd
}
try{
Thread.sleep(2000); //takes a little while to switch
}catch(Exception e){
System.out.println(e.toString());
}
cBoss.Attack(); //boss attacks you
if (cPlayer.getHitPoint()==0) //if your health points equal 0
{
gameStatus=1; //gameStatus is set to 1
CardLayout cl = (CardLayout)(this.getParent().getLayout()); //lets you switch panels
cl.show(this.getParent(), "MsgWnd"); //sets the panel to MsgWnd
MainWnd.cMsg.Init(); //displays the MsgWnd
}
}
// Variables declaration - do not modify
private javax.swing.JLabel jLblBH;
private javax.swing.JLabel jLblBP;
private javax.swing.JLabel jLblBoss;
private javax.swing.JLabel jLblLevel;
private javax.swing.JLabel jLblPH;
private javax.swing.JLabel jLblPP;
private javax.swing.JLabel jLblPlayer;
private javax.swing.JLabel jLblVS;
private javax.swing.JButton jbtnAttack;
// End of variables declaration
}
-
I'll try and explain polymorphism to you, as I understand it.
Imagine you have a few classes called "Triangle", "Circle" and "Square".
The classes Triangle, Circle and Square all have the same behaviour, a rotate() method.
Because of this you might want to create a superclass called "Shape" and stick the rotate() method in there so that Triangle, Circle and Square can inherit from Shape and therefore inherit the rotate() method.
This will give us something like the following:
http : // img27.imageshack.us/my.php?image=poly1.jpg
Now imagine that later on in your program you create a method that you want to take a shape arguement. Without polymorphism you might approach it like this by overloading the method:
Code:
public void genericMethod(Circle c)
{
// Do some generic stuff
c.rotate();
}
public void genericMethod(Triangle t)
{
// Do some generic stuff
t.rotate();
}
public void genericMethod(Square s)
{
// Do some generic stuff
s.rotate();
}
However, with polymorphism you can do this:
Code:
genericMethod(Shape a)
{
// Do some generic stuff
a.rotate();
};
Now imagine that during runtime, the method (the one that accepts a Shape) is called and a circle is passed into the method:
Code:
Circle myCircle = new Circle();
genericMethod(myCircle);
Hey wait a minute, you've said that genericMethod accepts a shape object, not a Circle!
Well that is the joy of polymorphism, the reference type can be a superclass of the object type!
That means
Code:
Shape myShape = new Circle();
Shape myShape = new Triangle();
Shape myShape = new Square();
are all valid!
Now you remember that Circle, Triangle and Square all inherited their rotate() method from Shape? Imagine that the rotate method was overridden and the Circle, Triangle and Square all rotated in different ways.
So if we use a superclass reference to reference a subclass object. For example:
Shape myShape = new Circle();
genericShape(myShape);
how does the JVM know which version of rotate() to call?
Well the answer is that it calls the most specific version. Well what is the most specific version you might ask?
Think of the most specific version as the lowest relevant version of the method found in the inheritance tree.
Remember our simple diagram:
http : //img27.imageshack.us/my.php?image=poly1.jpg
In our example we have:
Code:
[B]Shape [/B]myShape = new [B]Circle[/B();
genericMethod(myShape);
You'll notice that myShape's rotate() method is called by genericMethod. So how does the JVM know what version of rotate() to call? The one in Shape? Or the overridden one in Circle?
The JVM checks Circle to see if it has a rotate() method, and it does! This is the lowest relevant version found on the inheritance tree.
If Circle hadn't of had a rotate() method, then it would have moved up the inheritance tree to check to see if Shape had a rotate() method which it does and this version would have been called.
And don't worry about a version of the method not being found, the compiler will guarantee that a particular method is callable for a specific reference type!
I hope this made sense and helped?
Note to the moderators/admins, sorry for bypassing the image/link restriction you have. Please delete the links if you feel it is necessary and I'll replace it with ascii art!
-
Wow, thanks a lot! That helped me out tremendously and now I understand polymorphism!
-
No worries, glad it helped! :)
-
Wolf Brother, that is an excelent overview of polymorphism. So much of what I've read about it makes it over complicated and you simplified it nicely.
-
Thanks for the positive feedback logicbug, it's much appreciated!