Inheritance in Java
Inheritance in Java
class Eml{
int a=4;
}
class u extends Eml{
int b=6;
public static void main(String args[]){
u p=new u();
System.out.println(“hsjjs:"+p.a);
System.out.println(“dfdf:"+p.b);
}
}
Protected Member
• In java programming one derived class can extends only one base
class because java programming does not support multiple
inheritance through the concept of classes, but it can be supported
through the concept of Interface.
• Whenever we develop any inheritance application first create an
object of bottom most derived class but not for top most base class.
• When we create an object of bottom most derived class, first we
get the memory space for the data members of top most base
class, and then we get the memory space for data member of other
bottom most derived class.
• Bottom most derived class contains logical appearance for the data
members of all top most base classes.
• If we do not want to give the features of base class to the derived
class then the definition of the base class must be preceded by final
hence final base classes are not reusable or not inheritable.
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();
}
} OUTPUT:- Product=200
• If we are do not want to give some of the features of base class to derived
class than such features of base class must be as private hence private
features of base class are not inheritable or accessible in derived class.
• Data members and methods of a base class can be inherited into the
derived class but constructors of base class can not be inherited because
every constructor of a class is made for initializing its own data members
but not made for initializing the data members of other classes.
• An object of base class can contain details about features of same class
but an object of base class never contains the details about special
features of its derived class (this concept is known as scope of base class
object).
• For each and every class in java there exists an implicit predefined super
class called java.lang.Object. because it providers garbage collection
facilities to its sub classes for collecting un-used memory space and
improved the performance of java application.
Important facts about inheritance in Java