Skip to Main Content

Understanding of casting

rahulrasFeb 4 2014 — edited Feb 4 2014

Hi All,

I am trying out things on Java and want to understand more about casting.

Please see the following code

class Parent {
    public void mesg () {
    System.out.println("Parent Message");
}
}

class Child extends Parent {
    public void mesg () {
    System.out.println("Child Message");
}
    public void nextMesg () {
    System.out.println("Child next Message");
}
}

class c1 {

   public static void main (String[] args) {
   Parent p1 = new Parent();
   p1.mesg() ;
   Child c1 = new Child();
   c1.mesg();
   p1 = c1 ;
   p1.mesg() ;
   p1 = (Parent) c1 ;
   // p1.nextMesg();
   p1.mesg() ;
   }
}

If I uncomment the one commented line (4th from end, p1.nextMesg() ), this code will not compile.

I understand that, when I assign c1 to p1, overridden method will be called from the object originally created (i.e. Child object). What is the use of casting? Does it makes any difference anywhere? How?

Thanks in advance

Comments
Post Details
Added on Feb 4 2014
2 comments
1,454 views