Results 1 to 6 of 6
  1. #1
    AWPtic is offline Member
    Join Date
    Mar 2009
    Posts
    39
    Rep Power
    0

    Default 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.

    Java 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                   
    
    }

  2. #2
    Wolf_Brother is offline Member
    Join Date
    Apr 2009
    Posts
    9
    Rep Power
    0

    Default

    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:

    Java 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:

    Java 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:

    Java 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

    Java 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:
    Java 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!

  3. #3
    AWPtic is offline Member
    Join Date
    Mar 2009
    Posts
    39
    Rep Power
    0

    Default

    Wow, thanks a lot! That helped me out tremendously and now I understand polymorphism!

  4. #4
    Wolf_Brother is offline Member
    Join Date
    Apr 2009
    Posts
    9
    Rep Power
    0

    Default

    No worries, glad it helped! :)

  5. #5
    logicbug's Avatar
    logicbug is offline Member
    Join Date
    Jan 2009
    Location
    The Great White North, eh?
    Posts
    76
    Rep Power
    0

    Default

    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.

  6. #6
    Wolf_Brother is offline Member
    Join Date
    Apr 2009
    Posts
    9
    Rep Power
    0

    Default

    Thanks for the positive feedback logicbug, it's much appreciated!

Similar Threads

  1. question about polymorphism
    By becky in forum New To Java
    Replies: 4
    Last Post: 02-11-2009, 11:59 PM
  2. inheritance and polymorphism
    By tester in forum Eclipse
    Replies: 1
    Last Post: 12-21-2008, 05:58 AM
  3. what is polymorphism
    By Nari in forum New To Java
    Replies: 5
    Last Post: 04-04-2008, 04:14 AM
  4. Relation between Polymorphism and Inheritance
    By janakiram.attuluri in forum Advanced Java
    Replies: 1
    Last Post: 12-27-2007, 12:32 AM
  5. what's polymorphism?
    By christina in forum New To Java
    Replies: 2
    Last Post: 08-05-2007, 11:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •