my code is:-
class Building{}
class Barn extends Building{
public static void main(String[]args){
Building build1 = new Building();
Barn bar1 = new Barn();
Barn bar2 = (Barn)build1;
Object obj1 = (Object)build1;
String str1 = (String)build1; //also an error over here
Building build2 = (Building)bar1;
}
}
I am new to Java. so please can anyone explain me how the instantiation is being carried out here, like how the access is been given to each of the objects.
Also there is an error in the code please help me to rectify it too.
Given this
Barn bar2 = (Barn)build1;The part after the equal((Barn)build1) means that you are typecasting build1 from type Building to the type Barn and passing it’s value to bar2.
You could do that because any Barn is a Building, as you extended in class definition (Barn extends Building). You can also typecast any class type to Object class, because in Java, all classes extends from Object, aka everything is a Object.
You are having that error when trying to cast it as String because Building has no conection with String class. Got it?