why downcast object and run time polymorphism

Class Parent{
start(){}
}
Class Child extends Parent{
start(){
//override in child
}
processChildMethod(){//not overriden by parent method
}

}

Parent p= new Child();


Child c=(Child)p// why we do like this

c.processChildMethod();

my quwstion is  why we downcase like this

Child c=(Child)p


Child ch=new Child();
ch.processChildMethod()
above is enough right?
please advisse
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZoppoCommented:
Hi gudii9,

>> Child c=(Child)p// why we do like this

Because p.processChildMethod() cannot be called, because p is of type Parent, which doesn't have a processChildMethod().

A way around this is to implement this as virtual function in Parent and override it in Child. Which way to use depends, i.e. if the Parent class must not be changed for any reason, it is not possible to add a virtual function.

ZOPPO

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
Child ch=new Child();
ch.processChildMethod()

we could simply do like above right
instead of doing as below
Parent p= new Child();


Child c=(Child)p

c.processChildMethod();

please advise
Julian HansenCommented:
If you do this
Parent p= new Child();

Open in new window

Then this is unnecessary
Child c=(Child)p

Open in new window

I think you meant
Parent p= new Parent();
Child c=(Child)p

Open in new window

The whole point of the cast is to tell the compiler that it must view p as being of type Child so that the processChildMethod() method is available. In its native form p (of type Parent) does not have such a method so the compiler will error. By casting to Child the method is available.
Casting p of type Child to Child - does nothing.
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

ZoppoCommented:
Yes. You only need to do this in cases where you don't have a Child object, i.e. in a function, which has a Parent as argument.

Anyway: the sample is not good and probably a bit confuzing, especially for beginners. In object orientated programming derived classes can be seen as specialization of more generic base classes. For example both a car and an airplance are vehicles, so it is rational to derive classes for cars and airplanes from vehicles, but it wouldn't make sense to derive an airplane from a car. The same goes for your example. A Child is not a specialization of a Parent. Better would be a sample where Child (and Parent) are derived from a class Person.

I mention this only because it is sometimes difficult to imagine and understand abstract structures or relations if the terms used describe different structures or relations in reality. The problem becomes even worse if terms are used which describes entities, which can be both at the same time, i.e. in reality every parent is a child too, and every child can be a parent too, st simply makes no sense to derive childs from parents.

Often used examples, which makes it much easier to imagine are i.e.:

- simple issues with only one derivation level:
  geometric figures, with derived classes like circles, rectangles, triangles.

- bit more complext issue, with a class hierarchy with higher derivation-depths:
  animals, from animals it possible to derive i.e. mammals, fishes, insects, ..., from mammals one can derive dogs, cats, pigs, a.s.o.

Or just simply Base/Derived or BaseClass/SubClass/SubSubClass ...

This makes it easier to understand. I.e. a Animal class could imlement a virtual function CanFly(), for i.e. a derived class Birds could override this function an return ture, while another derived class Fishs implements one, which returns fall. If you now have a function which is used for all kinds of animals, i.e. Zoo::NeedsCage( Animal a ) can return 'a.CanFly()', so Zoo::NeedsCage returns true if a is a Bird and False if a is a Fish, allthough Zoo::NeedsCage doesn't even know Birds or Fishes.

ZOPPO
gudii9Author Commented:
http://www.codejava.net/java-core/the-java-language/what-is-upcasting-and-downcasting-in-java

i was checking herew
how abstract class do not even single abstract method in it?

public interface Mammal {
      public void eat();

      public void move();

      public void sleep();
}
 
Animal is the abstract class:
public abstract class Animal implements Mammal {
      public void eat() {
            System.out.println("Eating...");
      }

      public void move() {
            System.out.println("Moving...");
      }

      public void sleep() {
            System.out.println("Sleeping...");
      }

}

Please advise
gudii9Author Commented:
I think you meant
Parent p= new Parent();
Child c=(Child)p

this make sense as parent p do not have reference to non overriden methods of child we are down casting parent p to child c and then invoking child non overridden method
ZoppoCommented:
Sorry, I don't want to comment the code, I just want to repeat and encourage my opinion about bad examples, because this IMO is again a very bad I, why the hell should someone derive Animals from Mammals. Every mammal is an animal, not every animal is a mammal, so mammal is the specialization, not the more generic base.
gudii9Author Commented:
any better link/resource with sample code to understand this completely?
ZoppoCommented:
Well, the exsample is not wrong, it's just my opinion that it's not good to use contra-intuitve exsamples. I wouldn't have critized the exactly same exsample if only the word 'mammal' and 'animal' were swapped.

I have not much experience with C#, but I guess a probably good tutorial about classes could be http://www.blackwasp.co.uk/csharpobjectoriented.aspx - it's a bit lot to read (IMO it's not to hard since it's divided in small chapters), but since classes are the basic concept of every OO language, it's for sure worthwhile to spend some time/effort in order to really understand OOP.
gudii9Author Commented:
I think you meant Parent p= new Parent();
Child c=(Child)p
i mean as below actually


Class Parent{
start(){}
}
Class Child extends Parent{
start(){
//override in child
}
processChildMethod(){//not overriden by parent method
}

}

Parent p= new Child();


Child c=(Child)p// why we do like this

c.processChildMethod();

Open in new window

gudii9Author Commented:
If you do this
Parent p= new Child();

Select all
 
Open in new window

Then this is unnecessary
Child c=(Child)p

Open in new window


why it is not necessary? can you please elaborate?
Julian HansenCommented:
Child c=(Child)p// why we do like this

Open in new window

Makes no sense. p is already of type Child by line 2 - I stand by my earlier post.
gudii9Author Commented:
Parent p= new Child();

above is parent reference but child object type right?

if i do as below
Child c=(Child)p
it means i am casting same child type to again child type?
ZoppoCommented:
Yes, p is a reference of type Parent which references an object instance created from class Child.

This means: with p only member functions can be called which are known in the class Parent. The class Parent cannot know any functions which are declared in Child, Parent only knows member functions it declares itself.

So, if you know the p references a Child-instance you can cast p to a reference of type Child and call Child's member functions with the Child reference returned by the cast.

BTW: It is dangerous and error-prone to use such casting, since if p is not a reference to a Child- or Child-derived instance the behavior is undefined, i.e. in C++ this would crash. It's better to use virtual functions, they allow to do the same in a type-safe way.
gudii9Author Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
System Programming

From novice to tech pro — start learning today.