Menu
Topics Index
...
`


Class Inheritance >
Siva Nookala - 12 Apr 2016
The Java Class Inheritance supports the 'is-a relation'. Every sub-class object is also a super-class object, but every super-class object need not be a sub-class object. e.g., Every Movie is an Entertainment, but every Entertainment need not be a Movie, similarly, every Drama is an Entertainment, but every Entertainment need not be a Drama.

Since every sub-class object is also a super-class object, we can use the sub-class object where we use the super-class object.
public void printName(Entertainment e)
{
    System.out.println("Name of the entertainment is " + e.name);
}

Movie businessMan = new Movie();
businessMan.name = "Business Man";
businessMan.directorName = "Puri Jagannadh";

Drama devdas = new Drama();
devdas.name = "Devdas";

printName(businessMan); // Calling printName method by passing the Movie object
printName(devdas); // Calling printName method by passing the Drama object
Here printName is a method which takes any object of type Entertainment as a parameter. Since businessMan is an object of Movie, so it is also an object of Entertainment, so it can be passed as a parameter for the method printName. Similalry, devdas is also an object of Drama, which in turn is an object of Entertainment, so it can also be passed as a parameter.
public void printMovie(Movie m)
{
    System.out.println(m.directorName + " is the director for movie " + m.name);
}

Movie businessMan = new Movie();
businessMan.name = "Business Man";
businessMan.directorName = "Puri Jagannadh";

Drama devdas = new Drama();
devdas.name = "Devdas";

printMovie(businessMan); // Calling printMovie method by passing the Movie object
printMovie(devdas); // THIS WON'T WORK SINCE DRAMA IS NOT A MOVIE
Here we created a printMovie method, which takes any object of type Movie as a parameter. Since businessMan is an object of type Movie, it can be passed as a parameter. But devdas is an object of type Drama and since Drama is not a Movie, it can not be passed a parameter. Please note that passing parameter of different type will cause a compilation error. The example Passing Sub Class Object As Super Class Reference shows how the comparison of the entertainments can be done using a method.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.