Based on reusing the data members from one class to another class in JAVA we have three types of relationships. They are is-a relationship, has-a relationship and uses-a relationship.
Inheritance is the technique which allows us to inherit the data members and methods from base class to derived class.
A Derived class is one which contains some of features of its own plus some of the data members from base class
class <clsname-2> extends <clsname-1> { Variable declaration; Method definition; };
Here, clsname-1 and clsname-2 represents derived class and base class respectively.
Extends is a keyword which is used for inheriting the data members and methods from base class to the derived class and it also improves functionality of derived class.
Note:
Whenever we develop any inheritance application, it is always recommended to create an object of bottom most derived class. Since, bottom most derived class contains all the features from its super classes.
Whenever we inherit the base class members into derived class, when we creates an object of derived class, JVM always creates the memory space for base class members first and later memory space will be created for derived class members.
For example:
class c1; { int a; void f1() { .......; } }; class c2 extends c1 { int b; void f2() { .......; } };
Note:
Write a JAVA program computes sum of two numbers using inheritance?
Answer:
class Bc { int a; }; class Dc extends Bc { int b; void set (int x, int y) { a=x; b=y; } void sum () { System.out.println ("SUM = "+(a+b)); } }; class InDemo { public static void main (String k []) { int n1=Integer.parseInt (k [0]); int n2=Integer.parseInt (k [1]); Dc do1=new Dc (); do1.set (n1, n2); do1.sum (); } };
For every class in JAVA we have a super class called object class. The purpose of object class is that it provides garbage collector for collecting unreferenced memory locations from the derived classes.