AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
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 ?.



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
profile MOHAMMAD SALEEM BASHA - anyforum.in MOHAMMAD SALEEM BASHA
267150
up-rate
5
down-rate

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
profile Garima Gupta - anyforum.in Garima Gupta
596129026017
Reply This Thread
up-rate
4
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in