why downcast object and run time polymorphism

gudii9
gudii9 used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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

Author

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
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
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.
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

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

Author

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

Author

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
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.

Author

Commented:
any better link/resource with sample code to understand this completely?
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.

Author

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

Author

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?
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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.

Author

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?
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial