Types of Inheritance Tutorial Java


Types of Inheritance

There exists basically three types of inheritance.

  1. Multilevel inheritance
  2. Multiple inheritance
  3. Hierarchical inheritance

1. In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases.
2. In multiple inheritance, one class directly extends more than one class.
3. In hierarchical inheritance one class is extended by more than one class.

For a fresher, it will be very confusing, no doubt. Let us go in detail of each one programmatically. Remember, to learn Java, C++ knowledge is not at all required. In fact, you learn OOPs concepts through C++ syntax in C++ and through Java syntax in Java. That is all.

1. Multilevel Inheritance

In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains.

	
class Aves
{
  public void nature()
  {
    System.out.println("Generally, Aves fly");
  }
}
class Bird extends Aves
{ 
  public void eat()
  {
    System.out.println("Eats to live");
  }
}
public class Parrot extends Bird
{
  public void food()
  {
    System.out.println("Parrot eats seeds and fruits");
  }
  public static void main(String args[])
  {
    Parrot p1 = new Parrot();
    p1.food();                       // calling its own
    p1.eat();                        // calling super class Bird method
    p1.nature();                     // calling super class Aves method
  }
}
Types of Inheritance
Output screen of Parrot.java

Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot as a subclass can make use of the methods of Bird and Aves. Bird can make use of the methods of Aves only, but Aves as a super class cannot access subclass members. Following figure gives a schematic representation of the multilevel hierarchy with the classes involved in the program.


Types of Inheritance

2. Multiple Inheritance

In multiple inheritance, one class extends multiple classes. Java does not support multiple inheritance but C++ supports. The above program can be modified to illustrate multiple inheritance. The following program does not work.

                    
calss Aves   {   }
class Bird   {   }
public class Parrot extends Aves, Bird  {   }

In the above code, Parrot extends both Aves and Bird. This is not supported by Java and the above code raises compilation error. Following is the schematic representation.


Types of Inheritance

Note: Java supports multiple inheritance partially through interfaces.

3. Hierarchical Inheritance

In hierarchical type of inheritance, one class is extended by many subclasses. It is one-to-many relationship. A realtime example is available at dynamic binding.

class Aves
{
  public void fly()
  {
    System.out.println("Generally, aves fly");
  }
}
class Parrot extends Aves
{
  public void eat()
  {
    System.out.println("Parrot eats fruits and seeds");
  }
}
class Vulture extends Aves
{
  public void vision()
  {
    System.out.println("Vulture can see from high altitudes");
  }
}
public class FlyingCreatures
{
  public static void main(String args[])
  {	                                                // all the following code is composition for FlyingCreatures			
    Parrot p1 = new Parrot();
    p1.eat();                                         // calling its own member
    p1.fly();                 
                                                        // calling super class member by inheritance
    Vulture v1 = new Vulture();
    v1.vision();                                    // calling its own member
    v1.fly();	                // calling super class member by inheritance
  }
}
Types of Inheritance
Output screen of FlyingCreatures.java

In the above code, Aves class is extended by two classes – Parrot and Vulture. Both classes can make use of the methods of Aves. Even though the Parrot and Vulture are subclasses of the same class Aves, but still they cannot make use of each other members. Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make use of other members as between them no inheritance is involved (like two sons of a father; one son's property cannot be shared by other but both can share the property of father). Following is the schematic representation of the classes involved.


Types of Inheritance

Dynamic binding and dynamic polymorphism use hierarchical inheritance.

Disadvantages of Inheritance

  1. Both classes (super and subclasses) are tightly-coupled.
  2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other.
  3. Changing the code in super class method also affects the subclass functionality.
  4. If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.

70 thoughts on “Types of Inheritance Tutorial Java”

  1. Correct the mistake in Multi-level Inheritence
    “but Parrot as a super class cannot access subclass members”
    should be
    “but Aves as a super class cannot access subclass members”

  2. Create a class called Employee with attributes and another one having a name of your choice which can use the atrributes in the first Employee class

  3. nice understanding subject.lord will help u a lot to do like this concepts.rambabu mca sree vidyanikethan engineering college.

    1. You mean is it compulsory to support for an OOPS language? Two features were kept in mind by the Java designers always – a) to make Java platform-independent (already achieved) and b) to make Java simple to practice. Towards the second goal, they removed goto (which is against a structured programming), pointers, multiple inheritance and introduced implicit garbage collection. Multiple inheritance introduces a confusing concept called virtual functions. To avoid virtual functions menace, they avoided multiple inheritance. Still they are aware of the loss; they support through interfaces. Regarding the simplicity of Java, I can write pages.

  4. hai,
    can u explain in brief with examples and need of upcasting and downcasting of objects in java..

    plz..

    1. http://way2java.com/casting-operations/object-casting/

      Many places of Java, the methods return the required object as an object of Object class. For example, the get() methods of DS, lookup() method of RMI, in Hibernate and Spring etc, because JRE does not know, exactly what object is to returned until program execution. The JRE converts, for example, Student object into an object of Object class and returns. Now you down cast and use in your program.

      What JRE does internallly:
      Student std1 = new Student();
      Object obj1 = std1;

      Now obj1 is returned. You do the following.

      Student std2 (Student) obj1;

      If you are at Hyderabad, meet me, I will give a better explanation very from the basics.

    1. If you are a C or C++ programmer, you might have found much of the syntax of Java, particularly at the level of operators and statements, to be familiar. Because Java and C are so similar in some ways, it is important for C and C++ programmers to understand where the similarities end. There are a number of important differences between C and Java, which are summarized in the following list:
      No preprocessor
      Java does not include a preprocessor and does not define any analogs of the define, #include, and #ifdef directives. Constant definitions are replaced with static final fields in Java. (refer java.lang.Math.PI field for an example.) Macro definitions are not available in Java, but advanced compiler technology and inlining has made them less useful. Java does not require an #include directive because Java has no header files. Java class files contain both the class API and the class implementation, and the compiler reads API information from class files as necessary. Java lacks any form of conditional compilation, but its cross-platform portability means that this feature is very rarely needed.
      No global variables
      Java defines a very clean namespace. Packages contain classes, classes contain fields and methods, and methods contain local variables. But there are no global variables in Java, and, thus, there is no possibility of namespace collisions among those variables. Global variables are known as instance variables.
      Well-defined primitive type sizes
      All the primitive types in Java have well-defined sizes. In C, the size of short, int, and long types is platform-dependent, which hampers portability.
      No pointers
      Java classes and arrays are reference types, and references to objects and arrays are same as pointers in C. Unlike C pointers, however, references in Java are entirely opaque. There is no way to convert a reference to a primitive type, and a reference cannot be incremented or decremented. There is no address-of operator like &, dereference operator like * or −>, or sizeof operator. Pointers are a notorious source of bugs. Eliminating them simplifies the language and makes Java programs more robust and secure.
      Garbage collection
      The Java Virtual Machine performs garbage collection so that Java programmers do not have to explicitly manage the memory used by all objects and arrays. This feature eliminates another entire category of common bugs and all but eliminates memory leaks from Java programs.
      No goto statement
      Java doesn’t support a goto statement. Use of goto except in certain well-defined circumstances is regarded as poor programming practice. Java adds exception handling and labeled break and continue statements to the flow-control statements offered by C. These are a good substitute for goto.
      Variable declarations anywhere
      C requires local variable declarations to be made at the beginning of a method or block, while Java allows them anywhere in a method or block. Many programmers prefer to keep all their variable declarations grouped together at the top of a method, however.
      Forward references
      The Java compiler is smarter than the C compiler, in that it allows methods to be invoked before they are defined. This eliminates the need to declare functions in a header file before defining them in a program file, as is done in C.
      Method overloading
      Java programs can define multiple methods with the same name, as long as the methods have different parameter lists.
      No struct and union types
      Java doesn’t support C struct and union types. A Java class can be thought of as an enhanced struct, however.
      No enumerated types
      Java doesn’t support the enum keyword used in C to define types that consist of fixed sets of named values. This is surprising for a strongly typed language like Java, but there are ways to simulate this feature with object constants. (Enums introduced from JDK 1.5)
      No bitfields
      Java doesn’t support the (infrequently used) ability of C to specify the number of individual bits occupied by fields of a struct.
      No typedef
      Java doesn’t support the typedef keyword used in C to define aliases for type names. Java’s lack of pointers makes its type-naming scheme simpler and more consistent than C’s, however, so many of the common uses of typedef are not really necessary in Java.
      No method pointers
      C allows you to store the address of a function in a variable and pass this function pointer to other functions. You cannot do this with Java methods, but you can often achieve similar results by passing an object that implements a particular interface. Also, a Java method can be represented and invoked through a java.lang.reflect.Method object.
      No variable-length argument lists
      Java doesn’t allow you to define methods such as C’s printf() that take a variable number of arguments. Method overloading allows you to simulate C varargs functions for simple cases, but there’s no general replacement for this feature.
      Operators
      Java adds a new right shift operator >>> which inserts zeroes at the top end.
      The + operator scan be used to concatenate strings.
      Java adds another operator instanceof to identify objects.
      Operator overloading is not possible in Java.
      Classes
      Class definitions take the similar form in Java as in C++, but there is no closing semicolon.
      There is not scope resolution operator :: in Java.
      No destructors in Java
      No templates in Java.
      Inheritance in Java has the same effect an in C++, but the syntax is different.
      Java does not provide direct support for multiple inheritance. We can accomplish
      multiple inheritance by using interfaces.
      All instance variables have default values
      We need not externally define storage for static members like we do in C++.
      A class in Java can have an access specifier to determine whether it is visible outside the file.
      Arrays
      Arrays are quite different in Java. Array boundaries are strictly enforced. Attempting to
      read past the end of an array produces an error.
      One array can be assigned to another in Java.
      Strings
      Strings in C/C++ are arrays of characters, terminated by a null character. But strings in
      Java are objects.
      Strings can be concatenated with + operator.

      Differences between C and Java in a nutshell
      1. C is a procedural language, Java is object oriented
      2. C’s main structuring element are functions in files. Java organizes code in classes and packages, thereby providing better namespaces.
      3. C code gets compiled into machine code for a specific CPU. Java code gets compiled into bytecode which is interpreted on a virtual machine (JVM). Java code can get compiled into machine code as well (just-in-time compilers etc.)
      4. C does not have exceptions. Errors are handled through return codes.
      5. C types like structures (objects without methods) can be allocated on the stack. Java needs to allocate all non-primitives on the heap using expensive memory management functions (e.g. “new”).
      6. Arrays and strings in C are not bounds-checked. It is the programmers responsibility to stay within the allocated bounds
      7. lets programmers access memory addresses directly through the use of POINTERS. Pointers are variables which contain a memory address. Text (code), data, heap and stack areas are all within a programmers reach. Java lets only the virtual machine access a programs stack, e.g. to perform security checks.
      8. Java primitive types are fixed in length. C types can vary per machine. This lets C take maximum use of hardware specifics (e.g. 16 bit register size vs. 32 bit register size). It also creates portability problems.
      9. C has a preprocessor and include files. The preprocess works like a macro processor which substitutes macros in the program file.

  5. Thanks sir, this site is really helpful for fresher . I wanna ask in my system DataInputStream not working and in other system Scanner is not working why? and how can i resolve it. ?

  6. i was reding inheritance with two books bt cant be able 2 understand,,,,,,later i studied with this site its so easily explained
    thnkxxxxxxxx a lot…

  7. Yes we can overload main() but internally JVM is designed in such a way that it can call only main() of String type i.e public static void main(String[] args)
    eg:-
    class A
    {
    public static void main(String[] args)
    {
    System.out.println(“main() of String type”);
    }

    public static void main(int[] args)
    {
    System.out.println(“main() of Integer type”);
    }
    }

  8. We can create object without using new keyword by using following :-
    1.Class.forName();
    2.Reflection API.
    3.Factory Method.
    4.Cloning.

  9. ya…..this is nice…..but one thing is that..have asked 10 questions…
    but could not find answers….
    can i get answers?
    if so,,,will be nice…
    really superb to understand……..
    grade is pictorial representation……really good…..

  10. I wish you would have include some more examples…….But by this site its very easy to learn and understand….

    1. hello! i am rakesh patel.educational qualification is graduated from mahatmagandhi kashi vidhyapith,varanasi.

      1-what is constructor ,and what are you mean by call of value, call of refrence.

      1. Constructor is a Java programming construct called implicitly whenever an object is created. Call-by-reference (or pass-by-reference) and Call-by.value (or pass-by-value) have the same meaning (in Java) as that of C/C++. In Java, pass-by-reference is achieved through object assignment (not by pointers as in C/C++).

  11. Dominic Muthai Kithuka

    your site has most of the recommendable notes: easy to read and understand,detailed explanation and also beautiful colour.I really appreciate your website keep it up and God bless you. (Dominic from Kenya)

    1. S. Nageswara Rao, Sr.Faculty

      Hello Mr.Kithuka,

      Thanks for your comments. It encourages me to write more and more. You know this site I started only 20 days back working 19 hours per day. This, I feel, still infant state. Your negative comments like what you require and what not found will help me to improve the quality of the site. So, please write.

      Tell your friends are to derive knowledge out of the site.

      Best wishes of the day,
      S.Nageswara Rao
      Author, India.

Leave a Comment

Your email address will not be published.