Reputation: 1809
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.
Upvotes: 1
Views: 165
Reputation: 6620
Building b = (Building) (new Barn());
will have access to all of Building's members and fields, disregarding the added Barn fields (it's called downcasting);
Barn b = (Barn) (new Building());
will result in null-pointers when accessing barn-specific members or will leave them uninitialized... i kinda forgot what happens when you up-cast as it makes little sense to cast an Animal to a Cat unless you're expecting a Cat ;)
without specific methods or a debugger, you won't be able to notice the difference. I don't see a use-case in your code, only casting.
Upvotes: 0
Reputation: 5194
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?
Upvotes: 1
Reputation: 106430
You can't cast Building
as a type of String
. There's no relation between the two classes (inheritance, interface, etc).
It's certainly the case that a Building
is an Object
, but you'd lose information about your Building
object by casting it to Object
.
Instantiating a variable is right-to-left associative; you create a new instance of each object, and assign it to a variable. If you're doing a cast, then it's important to ensure that the type you're casting to relates to the type you're getting (i.e. casting an Object
as an Integer
- which may or may not work, depending on if what you get back could be reasonably cast as an Integer
).
Upvotes: 1