Reputation: 391
I have mentioned comments along the code line , that I want to understand i.e. as follows:
I didnt't understand this line of code :
Xyz obj3=(Xyz) obj1;
Abc
cannot be cast to Xyz
type . Compiled , but returns exception during execution : Xyz obj2=(Xyz)new Abc();
class Abc
{
Abc()
{
System.out.println(" Hello ");
}
void show()
{
System.out.println("Conco constructor w/ Super Class");
}
}
class Xyz extends Abc
{
Xyz()
{
System.out.println(" Hi ");
}
void display()
{
System.out.println("ConsNew3 constructor w/ Extends Class Conco");
}
public static void main(String arg[])
{
Xyz obj=new Xyz();
Abc obj1=new Xyz();
obj1.show();
Xyz obj3=(Xyz) obj1; // I didnt't understand this line of code
/*Xyz obj2=(Xyz)new Abc(); Abc cannot be cast to Xyz type . Compiled , but returns exception during execution */
}
}
Upvotes: 0
Views: 624
Reputation: 28747
In general humans are not very good in abstract notation, although programs require that.
A beginner (more correctly any person) in programming should not use abstract names like Abc, and Xyz, this even confuses advanced programmers.
Why not just rename Abc to Animal, and Xyz To Dog.
Then you have:
Dog obj3=(Dog) obj1; // works because Dog is an Animal.
Dog obj2=(Dog) new Animal(); // does not compile because not all Animals are Dogs
Upvotes: 2
Reputation: 2316
Xyz obj3=(Xyz) obj1;
this line works because Xyz
is an Abc
.
Xyz obj2=(Xyz)new Abc();
this line does not work because not all Abc
s are Xyz
s
As the comments mention it can make more sense to name things this way.
Abc == Animal
Xyz == Dog
Dog obj3 = (Dog) obj1;
obj1
was previously instantiated as a Dog
although it is being held by a more generic Animal
object. It still is an instance of a Dog
so it can be cast back to a Dog
.
Dog obj2 = (Dog) new Animal();
Animal
s are not necessarily Dog
s.
In order to avoid problems like this you can use the instanceof
operator. This tests whether a generic Object is an Instance of another, usually more specific Object.
You can use this as follows.
Object myGenericDog = new Dog();
Animal myAnimal = new Animal();
if(myGenericDog instanceof Animal){
myAnimal = (Animal) myGenericDog;
}
For future reference, in cases of both real and example code it is far more beneficial to the developer writing the code and any future developers who may end up maintaining the code to use descriptive class names. Note: Xyz
and Abc
are not descriptive. They introduce unnecessary complexity. You can improve your own code and examples by choosing names that are nouns and that describe the responsibility of your classes.
Upvotes: 1