Why java doesn't support multiple inheritance?:
Answer:
In c++ we have multiple inheritance ,but there is some problem (i.e ambiquity).
there is some confusion while accessing the members of particular class if we same members in both classes.
example in detail:
#include<iostream.h>
#include<conio.h>
class a1
{
public:
int a;
void display1()
{
cout<<"enter the value";
cin>>a;
cout<<"i am from class a="<<a;
}
};
class b
{
public:
int a;
void display1()
{ a=20;
cout<<" i am from class b="<<a;
}
};
class c:public a1,public b
{
public :
void display3()
{
cout<<" i am derived from where="<<a;
}
};
void main()
{
clrscr();
c c1 ;
c1.display1();
c1.display3();
getch();
}
class a1
{
public:
int a;
void display1()
{
cout<<"enter the value";
cin>>a;
cout<<"i am from class a="<<a;
}
};
class b
{
public:
int a;
void display1()
{ a=20;
cout<<" i am from class b="<<a;
}
};
class c:public a1,public b
{
public :
void display3()
{
cout<<" i am derived from where="<<a;
}
};
void main()
{
clrscr();
c c1 ;
c1.display1();
c1.display3();
getch();
}
you get like this:
Error: Member is ambiguous a1::a or b::a
Explanation:
I this,we have three classes named as a1,b,c here a1,b are the parent classes and c is the child class,so it form the multiple inheritance.when child class(c) try access the data member a at the time there is some confusion(i.e which class member was accessed either class a1 or class b) so the compiler leads to error.
solutions:
i) use scope resolution operator(::) to access particular class member.
ii)use virtual keyword
example:
#include<iostream.h>
#include<conio.h>
class a1
{
public:
int a;
void display1()
{
cout<<"enter the value";
cin>>a;
cout<<"i am from class a="<<a;
}
};
class b
{
public:
int a;
void display1()
{ a=20;
cout<<" i am from class b="<<a;
}
};
class c:public a1,public b
{
public :
void display3()
{
cout<<" i am derived from where="<<a1::a;
}
};
void main()
{
clrscr();
c c1 ;
c1.display1();
c1.display3();
getch();
}
#include<conio.h>
class a1
{
public:
int a;
void display1()
{
cout<<"enter the value";
cin>>a;
cout<<"i am from class a="<<a;
}
};
class b
{
public:
int a;
void display1()
{ a=20;
cout<<" i am from class b="<<a;
}
};
class c:public a1,public b
{
public :
void display3()
{
cout<<" i am derived from where="<<a1::a;
}
};
void main()
{
clrscr();
c c1 ;
c1.display1();
c1.display3();
getch();
}
output:
enter the value 30
i am from class a 30
i am derived from 30
Explanation:
in this program,we are clearly stated that (a1::a) a1 class member (a).
so there is no confusion.
that's why we wont allow multiple inheritance directly and we are implemented in indirect way(i.e) interface.