Types of Inheritance
There exists basically three types of inheritance.
- Multilevel inheritance
- Multiple inheritance
- 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
}
}

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.

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.

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
}
}

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.

Dynamic binding and dynamic polymorphism use hierarchical inheritance.
Disadvantages of Inheritance
- Both classes (super and subclasses) are tightly-coupled.
- As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other.
- Changing the code in super class method also affects the subclass functionality.
- 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.
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”
Yes, corrected. Thank you.
can you deeply explain what is the exact use of a constructor with an example?
See this link:
http://way2java.com/oops-concepts/java-tutorial-constructor-creation-example/
http://way2java.com/oops-concepts/constructors/java-constructor-2/
can java support multiple inheritance?
Basically Java does not support multiple inheritance; but supports partially through interfaces.
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
So, what you want from me?
i want to learn java but i dont know how to create programs will u give guidence.
Different between inheritance and polymorphism
Dynamic Polymorphism is achieved through inheritance. No inheritance, no dynamic polymorphism.
nice understanding subject.lord will help u a lot to do like this concepts.rambabu mca sree vidyanikethan engineering college.
Sir why java doesn’t support multiple inheritance through classes what is the problem?
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.
hai,
can u explain in brief with examples and need of upcasting and downcasting of objects in java..
plz..
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.
plz tellme main difference between c and java.
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.
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. ?
Scanner works with JDK 1.5 only. Send your DataInputStream code. It must work on all JDKs.
diffence between while,do-while,for in java
loop concept explain
It is the same as C/C++.
why we use Inheritance ?
Straight answer is to call somebody’s method with your class object. Or to say, code reusability.
can u plz give me the answer for return type of constructor?
Return type of a constructor is a class object.
what is difference between forloop, dowhileloop,whileloop in java
For these simple questions, refer any C/C++ control structures as Java follows the same as that of C/C++.
Return type of a constructor is class object.
Then why we don’t write any return type for constructor ?
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…
this is good site of knowladge
Nice to hear from you. Advice your friends also to derive the benefit of this web site.
it is really good website really very useful thanks to this website creator.
Constructor doesn’t have any return type not even void.
Yes we can establish multiple inheritance using interface.
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”);
}
}
Yes, you understood correctly.
We can create object without using new keyword by using following :-
1.Class.forName();
2.Reflection API.
3.Factory Method.
4.Cloning.
Yes, you are right.
The java language does not support multiple inheritance.
Yes, you are right. But supports through interfaces. Infact, Java proved that an OOP language can exist without the complex multiple inheritance.
very nice explanation.tanq
sir i would be very happy if u give me a chance to work with you wrt to programming and other stuffs……
OK with pleasure. Send your postings.
u rocks man …..easy example ..tanx a lot ..:D
Very best for learning so much simple one.Thanks
nice example for inheritance,very helpfull for fresher
Thanks. Tell your friends.
thanku….
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…..
Hello,
The answers will be activated on December 2nd. There is a restriction on publishing the data.
Thanks a lot Sir for your fruitful knowledge..
I wish you would have include some more examples…….But by this site its very easy to learn and understand….
very good example and easy to learn
Hello Arpita,
Nice to hear from you. Anything you require more, write me, I will place it. Advise also your friends about this web site.
thanks for this
there is multiple inheritance in java
Yes, it is mentioned, supports through interfaces..
thankku very nuch
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.
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++).
provide more example
This is very good site for inheritance example.
it is easy to read and understand,detailed explanation
very nice examples for all programs
Your comments are encouraging to improve the quality still.
Good I like this…
This is very good site for inheritance example.
it is easy to read and understand,detailed explanation
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)
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.