AF
Home
Tag
Submit Notes
Ask Anything
Login
Subscribe Us
A
ny
F
orum
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.
Follow @anyforumin
OOPs-inheritance: Regarding creation of objects for inherited classes in java?
class A {
}
class B extend A
{
}
class C
{
main()
{
A a=new B() ; //it is valid statement but vice-versa is not correct .May i know why B b=new A() is not correct
}
}
OOPs x 49
inheritance x 7
Posted On :
2016-08-15 11:55:49.0
MOHAMMAD SALEEM BASHA
269
15
0
5
Answers
A child class is always supposed to have some extra features or methods. If java allow to store parent class object on child class reference, it´s expected that we can call child class method but we can´t. For example we have parent class Animal, and Dog class has one extra method bark() which animal class don´t have. Now if we see
Dog dog=new Animal();
dog is expected to call bark() but we can´t, Java supports run-time polymorphism and Animal class don´t have bark() implementation. Everything will be very confusing. On the other hand if we do like this:
Animal a=new Cat();
Animal b=new Dog();
and in this manner we can call all general methods and extra methods implemented in respective child classes and it shows the abstraction also.
Posted On :
2016-08-15 23:01:49
Satisfied :
2 Yes
0 No
Garima Gupta
596
1295
54554
Reply This Thread
4
Post Answer
Please Login First to Post Answer:
Login
Answer:
anyforum.in