Inheritance: Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class(superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.
class A{ public void fun1(int x){ System.out.println("int in A"); }
}
class B extends A{ public void fun2(int x,int y){ fun1(6); // prints "int in A" System.out.println("int in B"); } } public class C{ public static void main(String[] args){ B obj= new B(); obj.fun2(2); } }
In the above example, class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.