Inheritance is a mechanism of creating a new class from an existing class by inheriting the features of existing class and adding additional features of its own. When a class is derived from an existing class, all the members of the superclass are automatically inherited in the subclass. However, it is also possible to restrict access to fields and method of the superclass in the subclass. This is possible by applying the access Specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The private members of the superclass remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the members of the subclass. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.
class Base
{
private int numl;//private member
public void setData(int n)
{
numl = n;//private member accessed within the class
}
public int getData()
{
return numl;//private member accessed within the class
}
}
class Derived extends Base
{
int num2 ;
public void product()
{
int num =getData();
System.out.println("product = " + (num2 * num));
}
}
public class PrivateInheritance
{
public static void main(String[] args)
{
Derived d = new Derived();
d.setData(20) ; //to set private member numl
d.num2 = 10 ;
d.product();
}
}
In the above program, numl is a private data field defined in the class Base. Only the methods setData () and getData () in the class Base can access this field directly by name from within its definition. However, it is not accessible to any other class including the Derived subclass.
In order to access the private field numl of the superclass Base in the method product () of the subclass Derived, we call the getData () method of the class Base as shown in the statement