- Creating a new class from existing class is known as
inheritance.
- Inheritance is used to achieve dynamic binding and
reusability.
- The class which is inherited is known as super class or parent
class and the class derived from the parent class is known as sub class or
child class.
- Inheritance is implemented using extends keyword.
Just take a look on below syntax.
class parent_class_name extends child_class_name
{
//body
}
- All the properties of
parent class come to child class if they are not private.
- An example about how inheritance is implemented in java is
given below.
class parent
{
String
name=”Mark”;
name=”Mark”;
}
class child extends parent
{
void
show()
show()
{
System.out.println(name);
}
public
static void main(String…s)
static void main(String…s)
{
child
c=new child();
c=new child();
c.show();
}
}
- In above example variable name is default
therefore it is accessible in child class. If we make name as private
then it will show error like “name has private access in parent”.
Types of Inheritance in Java
- There are three types of inheritance in java: single,
multilevel and hierarchical inheritance.
- In java, multiple inheritance is not supported by class.
Multiple inheritance can be implemented by Interface, later on we will discuss
about it.
Why multiple inheritance is not supported in java?
- In order to decrease the complexity and ambiguity, multiple
inheritance is not supported in java.
- Consider a situation in which we have three classes A, B and
C. Class C inherit class A and B. If classes A and B have a method with same
prototype and when we call this method in class C then it will cause ambiguity because
compiler will be confused that whether method from class A is called or method
from class B is called.