Win a copy of Functional Design and Architecture this week in the Functional programming forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Casting , why so? Any help?...More....

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class MyClass{
public static void main(String argv[]){
MyClass Obj1;
vbClass Obj2;

Obj1=new vbeClass();
Obj2=new vbClass();
//Obj1.abc();
Obj2.abc();
Obj2=(vbClass) Obj1;
//Now it is vbclass
//earlier it was vbeclass;same results
Obj2.abc();// How it is giving vbeClass->abc
}


}
class vbClass extends MyClass{
void abc(){System.out.println("vbClass->abc");}
}
class vbeClass extends vbClass{
void abc(){System.out.println("vbeClass->abc");}
}
Obj2.abc(); ==>> Output is vbeClass-abc
How ???
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by vb:
public class MyClass{
public static void main(String argv[]){
MyClass Obj1;
vbClass Obj2;

Obj1=new vbeClass();
Obj2=new vbClass();
//Obj1.abc();
Obj2.abc();
Obj2=(vbClass) Obj1;
//Now it is vbclass
//earlier it was vbeclass;same results
Obj2.abc();// How it is giving vbeClass->abc
}


}
class vbClass extends MyClass{
void abc(){System.out.println("vbClass->abc");}
}
class vbeClass extends vbClass{
void abc(){System.out.println("vbeClass->abc");}
}
Obj2.abc(); ==>> Output is vbeClass-abc
How ???


The Output is vbeClass-abc because Obj2 holds a reference to an instance of vbeClass.
Reason : Obj2=(vbClass) Obj1;
The above statement could not be written as Obj2 = Obj1 because the compile time type of Obj1 (i.e MyClass) is not assignment compatible with compile time type of Obj2 (i.e vbClass).
Therefore, a cast is required. Casting does not mean the Type of the Obj2 object is changed.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic