Results 1 to 3 of 3

Thread: polymorhism

  1. #1
    chairym is offline Member
    Join Date
    Apr 2012
    Posts
    2
    Rep Power
    0

    Default polymorhism

    Hello everyone, i am trying to learn java and i am little confused in polymorphism.. can someone please tell me when i pass the handler as a parameter and call the method and when i just call the method using that object(not as a parameter)?
    tnx
    Last edited by chairym; 04-21-2012 at 12:55 PM.

  2. #2
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default Re: polymorhism

    Here's an example to illustrate polymorphism. The rest of your question really has nothing to do with polymorphism.

    Java Code:
    interface Pet  {
       public String petIt();
    }
    
    class Dog implements Pet  {
      public String petIt()  {
        return "Ruff!  Ruff!";
      }
    }
    
    class Cat implements Pet  {
      public String petIt()  {
        return "Meow!";
      }
    }
    
    class petShop  {
      void main ()  {
          Dog sam = new Dog();
          Cat fluff = new Cat();
    
         Pet[] pets = {sam, fluff};  // Notice how this array of Pet has a Cat and a Dog in it? 
                                             // That is because both Cat and Dog are also Pet because the implement the Pet interface.
    
         for (Pet pet: pets)  {  // This loop is polymorphism in action.
             System.out.println(pet.petIt());           // This doesn't care which Pet it is, it will call the petIt() method for the particular instance.
          }      
      }
    }
    The output will look like this:
    Ruff! Ruff!
    Meow!

    I don't have time to link you right now, but the Oracle website has tutorials that explain about polymorphism and also about parameter passing.

  3. #3
    chairym is offline Member
    Join Date
    Apr 2012
    Posts
    2
    Rep Power
    0

    Default Re: polymorhism

    Ok thank u so much! :) (excuse me for the name i forgot to change it!)

Posting Permissions

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