What Is the Main Difference Between Inheritance and Polymorphism

What is the main difference between Inheritance and Polymorphism?

Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.

Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student. It gets a bit tricky, but if you do something like

Person p = new Student();
p.read();

the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

Note that details differ among languages. You can do inheritance in javascript for example, but its completely different than the way it works in Java.

Polymorphism vs Inheritance

In Java, the concepts of polymorphism and inheritance are "welded together"; in general, it does not have to be that way:

  • Polymorphism lets you call methods of a class without knowing the exact type of the class
  • Inheritance lets derived classes share interfaces and code of their base classes

There are languages where inheritance is decoupled from polymorphism:

  • In C++ you can inherit a class without producing polymorphic behavior (i.e. do not mark functions in the base class with virtual)
  • In Objective C you can implement a method on an unrelated class, and call it from a place that knows only the signature of the method.

Going back to Java, the reason to use polymorphism is decoupling your code from the details of the implementation of its counter-parties: for example, if you can write a method Feed(Animal animal) that works for all sorts of animals, the method would remain applicable when you add more subclasses or implementations of the Animal. This is in contrast to a Feed(Dog dog) method, that would be tightly coupled to dogs.

As far as the

Dog d = new Dog();

declaration goes, there is no general reason to avoid this if you know that the rest of your method deals specifically with dogs. However, in many cases the later is not the case: for example, your class or your methods would often be insensitive to the exact implementation, for example

List<Integer> numbers = new ArrayList<Integer>();

In cases like that, you can replace new ArrayList<Integer>() with new LinkedList<Integer>(), and know that your code is going to compile. In contrast, had your numbers list been declared as ArrayList<Integer> numbers, such switchover may not have been a certainty.

This is called "programming to an interface". There is a very good answer on Stack Overflow explaining it.

Difference between inheritance and polymorphism

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

  • when-best-to-use-an-interface-in-java

Java inheritance vs polymorphism

For your first part of the question I think Wikipedia provides a good definition:

In object-oriented programming, subtype polymorphism or inclusion
polymorphism is a concept in type theory wherein a name may denote
instances of many different classes as long as they are related by
some common super class. Inclusion polymorphism is generally
supported through subtyping, i.e., objects of different types are
entirely substitutable for objects of another type (their base
type(s)) and thus can be handled via a common interface.
Alternatively, inclusion polymorphism may be achieved through type
coercion, also known as type casting.

Another Wikipedia artile called Polymorphism in object-oriented programming seems to answer your questions very well. The second reference in this article called On Understanding Types, Data Abstraction, and Polymorphism also covers this matters in great detail.

This subtyping feature in Java is achieved, among other means, through inheritance of classes and interfaces. Although the subtyping features of Java may not be evident in terms of inheritance all the time. Take for example the cases of covariance and contravariance with generics. Also, arrays are Serializable and Cloneable although this is not evident anywhere in the type hierarchy. It can also be said that through primitive widening conversion, also numeric types in Java are polymorphic. And operator behave polimorphically depending on their operands.

At any rate, inheritance plays an important role in the implementation of some of this polymorphism.

Overloading vs Overriding

Your second part of the question seems to be about choosing the implementation of a given method. Evidently, if a class overrides a method and you create an instance of that class you want the overriden version of method to be invoked, even if you are accessing the object through a reference of the parent class.

The selection of the right implementation of method is done at runtime as you well pointed out, now the signature of the method to be invoked is decided at compile time. Since overloading is about different methods with the same name and different signature, that is why it is said that overriding method selection happens at compile time.

Overriding Method Selection at Compile Time

The Java Language Specification (JLS) in section 15.12 Method Invocation Expressions explains in detail the process that the compiler follows to choose the right method to invoke.

There, you will notice that this is a compile-time task. The JLS says in subsection 15.12.2:

This step uses the name of the method and the types of the argument expressions
to locate methods that are both accessible and applicable
There may be more than one such method, in which case the most specific one is chosen.

To verify the compile-time nature of this, you can do the following test.

Declare a class like this and compile it.

public class ChooseMethod {
public void doSomething(Number n){
System.out.println("Number");
}
}

Declare a second class that invokes a method of the first one and compile it.

public class MethodChooser {
public static void main(String[] args) {
ChooseMethod m = new ChooseMethod();
m.doSomething(10);
}
}

If you invoke the main, the output says Number.

Now, add a second more specific overloaded method to the ChooseMethod class, and recompile it (but do not recompile the other class).

public void doSomething(Integer i) {
System.out.println("Integer");
}

If you run the main again, the output is still Number.

Basically, because it was decided at compile time. If you recompile the MethodChooser class (the one with the main), and run the program again, the output will be Integer.

As such, if you want to force the selection of one of the overloaded methods, the type of the arguments must correspond with the type of the parameters at compile time, and not only at run time.

Overriding Method Selection at Run time

Again, the signature of the method is decided at compile time, but the actual implementation is decided at runtime.

Declare a class like this and compile it.

public class ChooseMethodA {
public void doSomething(Number n){
System.out.println("Number A");
}
}

Then declare a second extending class and compile:

public class ChooseMethodB extends ChooseMethodA {  }

And in the MethodChooser class you do:

public class MethodChooser {
public static void main(String[] args) {
ChooseMethodA m = new ChooseMethodB();
m.doSomething(10);
}
}

And if you run it you get the output Number A, and this is Ok, because the method has not been overriden in ChooseMethodB and therefore the implementation being invoked is that of ChooseMethodA.

Now, add an overriden method in MethodChooserB:

public void doSomething(Number n){
System.out.println("Number B");
}

And recompile just this one, and run the main method again.

Now, you get the output Number B

As such, the implementation was chosen at runtime, and not recompilation of the MethodChooser class was required.

What is the main difference between using inheritance and polymorphism to instantiate of an object of a subclass of Thread?

There is no difference AT ALL in the instantiation of the thread. The only difference is in the type of the variable that holds the reference to the thread.

First question: do you understand the difference between an object and a reference to an object? A variables is not the object, it holds a reference.

So the question is, do you want your program to treat the thread as a general Thread (first example) or as AnotherThread (second example)? Both of these are valid, it just depends on what you want to accomplish. In general, if subsequent code has no need to treat it specifically as AnotherThread, then programming to the Thread interface is preferred.

what's the difference between inheritance and polymorphism?

Let's use my favorite verb and we find:

http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29

http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx

Polymorphism and Inheritance are pivotal, need-to-be-ingrained and fundamental concepts to C# and object oriented programming. saying you know C# and not this is like knowing how to speak English and have no concept of what the alphabet is. Sorry to be blunt, but it is true.

From the Wiki link above (this is not mine), here is an example of Polymorphism (converted to C#...)

public class Animal
{
public virtual String talk() { return "Hi"; }
public string sing() { return "lalala"; }
}

public class Cat : Animal
{
public override String talk() { return "Meow!"; }
}

public class Dog : Animal
{
public override String talk() { return "Woof!"; }
public new string sing() { return "woofa woofa woooof"; }
}

public class CSharpExampleTestBecauseYouAskedForIt
{
public CSharpExampleTestBecauseYouAskedForIt()
{
write(new Cat());
write(new Dog());
}

public void write(Animal a) {
System.Diagnostics.Debug.WriteLine(a.talk());
}

}

inheritance and polymorphism c++

In this case, we have inheritance but no polymorphism:

struct SimpleBase {
int i;
int get() const { return i; }
};

struct SimpleDerived: public SimpleBase {
int get() const { return i + 7; }
};

an instance of SimpleBase (or a reference or pointer to it) is always exactly that, and the derived class can't change its behaviour. For example:

int foo(SimpleBase const &obj) { return obj.get(); }

will always call SimpleBase::get, even if I pass in an instance of the derived type.


Conversely, with polymorphism, a derived class can override base class methods with its own versions:

struct PolyBase {
int i;
virtual int get() const { return i; }
};

struct PolyDerived {
int get() const { return i + 7; }
};

int foo(PolyBase const &obj) { return obj.get(); }

Now foo calls a different method depending on the derived type passed in, without knowing which derived type it is.

So with polymorphism, a whole family of types can share a common interface, and you can write code once that operates on the interface, without having to know about all the different derived types.


The form of polymorphism shown above is run-time polymorphism: it generates code that figures out which implementation of each virtual function to call when it runs.

There is also compile-type polymorphism, which doesn't require inheritance at all, and instead uses templates.

Say you want to write a sorted container (like std::map) - you don't want to limit it to storing a particular data type, but you do need some way to compare two elements to see which is bigger.

The run-time approach might provide an abstract base class, like

struct LessThanComparable {
virtual bool operator< (LessThanComparable const &) const = 0;
};

and require every type you want to put in your container, to derive from this and implement operator<. Then, you can write if (a < b) in your container code, and the right function for the type you're storing will be called (*).

// requires inheritance from abstract base class,
// uses virtual call to operator<
bool less_than(LessThanComparable const &a, LessThanComparable const &b) {
return a < b;
}

The compile-type approach actually used (**) in the STL is to state that every stored type must model the LessThanComparable concept, by providing a suitable operator<. However, this is resolved at compile time, and no common base class is required.

// doesn't require any inheritance, doesn't use virtual function call,
template <typename T>
bool less_than(T const &a, T const &b) { return a < b; }

(*) note also that implementing operator< isn't trivial, because a < b can be called when a and b have different derived types. In the template version, we know they both have the same type T.

(**) ok, so the default std::less has the LessThanComparable requirement, or you can provide an alternative StrictWeakOrdering.

what is the difference between polymorphism and inheritance

Lets start with your example.

class A
{
public:
int a;
virtual void get()
{
cout<<"welcome";
}
};

class B:public A
{
a =a+1; //why it is called code reuse
void get() //why it is called overriding
{
cout<<"hi";
}
};

Inheritance: Here you are deriving class B from class A, this means that you can access all of its public variables and method.

a = a + 1

Here you are using variable a of class A, you are reusing the variable a in class B thereby achieving code reusability.

Polymorphism deals with how a program invokes a method depending on the things it has to perform: in your example you are overriding the method get() of class A with method get() of class B. So when you create an instance of Class B and call method get you'll get 'hi' in the console not 'welcome'

What is the difference between Multiple Inheritance and Polymorphism?

Like Ikke said, Multiple Inheritance has nothing to do with Polymorphism.

If I could draw a class diagram, Multiple Inheritance looks like this:

Base A    Base B
^ ^
\ /
\ /
Child

So, the class Child would inherit both attributes and behaviours from both classes. Many languages like Java and PHP don't allow this, but Python does.

Polymorphism, on the other hand, is when you can abstract out a specialisation. First of all, class diagram:

     Animal
^ ^
/ \
/ \
Cat Dog

And you may do the following:

// Assuming we have a pack of animals
// This is Java
for (Animal pet : pack)
pet.speak();

Each pet will say different things depending on the implementation.



Related Topics



Leave a reply



Submit