3

I was studying about polymorphism. I couldn't determine the analogy in Java about these two features.

Let's say Animal class is a concrete superclass with Cat and Dog as its subclasses. I know that this is a case of inheritance. But isn't Cat and Dog classes, polymorphs of Animal class?

I am well aware of interfaces in Java. I couldn't understand why interfaces are used instead of concrete classes to explain polymorphism. It could be that the whole purpose of creating interface is to create polymorphs but I want to know why interfaces and not concrete classes?

Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
h-rai
  • 3,636
  • 6
  • 52
  • 76
  • related question: http://stackoverflow.com/questions/6308178/what-is-the-main-difference-between-inheritance-and-polymorphism – akf Jun 11 '12 at 02:31

5 Answers5

7

Inheritance

class Animal{
  public void speak(){ System.out.println("Speaking something");}
}

class Person extends Animal{
 @Override
 public void speak(){ System.out.println("Hello..");}
}  

Polymorphism

Animal a  = new Person();
a.speak();// Hello

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class [..]


Why Interface ?

You know what needs to be done, but you want implementers to decide how to do it, You will let implementer implement the stuffs forcefully

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • So use of polymorphism is only when you assign an object of subclass to a reference of it's superclass? – h-rai Jun 11 '12 at 02:29
2

Interface uses one type of polymorphism ie, Method overriding.

Interfaces are often used as an contract of being commonly used methods.

Stephan
  • 41,764
  • 65
  • 238
  • 329
Nitin Dominic
  • 2,659
  • 1
  • 20
  • 22
1

I don't know that interfaces are the best way to explain polymorphism. Polymorphism is an outgrowth of inheritance. It's what happens from an observer's point of view when looking at a inheritance hierarchy. Every animal may be able to make a sound, but when the observer actually observes the animal making a sound, the cat meows and dog barks. And the small dog yips while the big dog yelps. Polymorphism is the ability to have these attributes exhibit themselves implicitly based on their position in inheritance hierarchy.

Interfaces are a way to achieve composition. You can add attributes to objects that other related or unrelated objects may or may not have. The dog is a drooler. While the cat is a scratcher. Other things that are not necessarily part of the animal inheritance hierarchy can also have these drooling and/or scratching attributes.

silijon
  • 922
  • 1
  • 8
  • 19
  • so apparently, not all the polymorphs have same superclass. is that right? – h-rai Jun 11 '12 at 02:45
  • interfaces are a technique for incorporating similar attributes across objects with different superclasses. but typically "polymorphism" refers to objects with a shared superclass. – silijon Jun 11 '12 at 21:33
1

Inheritance is implemented in Java as the simple extension of the methods/fields of a superclass or interface using the extends or implements keywords, respectively. Either way, you have access in the subclass to the public and protected data members of the superclass, and when acting on the subclass from the outside, only the public data members.

Taking your example, you could have definitions of several classes:

class Animal {
    private int location;

    public Animal() {
        location = 0;
    }

    public void move() {
        location += 10;
    }

    public int getLocation() {
        return location;
    }
}

class Dog extends Animal {
    @Override
    public void move() {
        setLocation(getLocation() + 5);
    }
 }

/*
 * The @Override flag is optional, but I prefer to put it there
 * to ensure that I am actually overriding a method or implementing
 * a method from an interface.
 */

class Cat extends Animal {
    @Override
    public void move() {
        setLocation(getLocation() + 15);
    }
}

So Dog and Cat both extend Animal - this is an inheritance relationship.

Polymorphism is something totally different. According to Wikipedia:

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior.

In simple English terms, this just means taking the same idea or action and implementing it differently based on the specific type of object that it is. In code:

public static void main(String[] args) {
    Animal animalArray = {
        new Animal(),
        new Cat(),
        new Dog()
    };

    for (Animal a : animalArray) {
        a.move();
    }

    System.out.println("Animal location: " + animalArray[0].getLocation());
    System.out.println("Cat location: " + animalArray[1].getLocation());
    System.out.println("Dog location: " + animalArray[2].getLocation));
}

This produces the output:

Animal location: 10
Cat location: 15
Dog location: 5

Note that each object, the Animal, the Cat, and the Dog are all accessed as Animals. This is possible because every class is or extends Animal, and each class will therefore always have the public method move(), which is simply redefined in some cases.

Interfaces work on the same philosophy; if a class extends an interface, it can be guaranteed to have some implementation of every method defined in the interface, and it can thus be used in terms of the methods that the interface implements.

Michael
  • 1,239
  • 9
  • 14
0

Pretend you have been hired to create a programming language, and this is one of the requirements:

1 > 3 should call code from the integer comparison library.
1.0 > 3.0 should call code from the floating point comparison library.
"McDonald" > "MacDonald" should call code from the locale-aware string comparison library.

That requirement is "polymorphism," where the same text (the > operator) does different things depending on circumstances (in this case, the type of the operands).

You could meet these requirements by having integers, floats, and character strings all derived from the same base class, and defining the base class as having a virtual comparison operator. This can get messy. If later on, the language user wants ...

blue > yellow

... to compile to code which performs color operations, the base class approach means saying that colors, strings, floats, and integers are all special cases of a more general base. I think that would be weird.

Another approach is to provide a way in the language for the application developer to create arbitrary types and say what operations they support, and for the library developer to provide functions for any types that support a set of operations. For example, you can write a sort routine for any type that supports comparison and assignment operators.

That approach is called Interfaces, and it has the virtue that it can work well with types that are really very different.

Thomas L Holaday
  • 13,614
  • 6
  • 40
  • 51