Upcasting and Downcasting in Java - Full Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to talk all about upcasting and downcasting in java we'll go over what they are how to use them and how to avoid some problems you might run into when implementing them into your code my name is john i'm a lead java software engineer and i love sharing what i've learned in a clear understandable way so of course if you like this video don't forget to subscribe so you don't miss each new java tutorial i also have a full java course available in a link down in the description if you're interested so first of all what exactly do we mean by upcasting and downcasting upcasting is when you take an object and cast it to its superclass type it's parent type and downcasting is when you take an object and cast it to one of its subtypes a child class let's talk about it with a concrete example so we have this animal class here all it has is one field a string name and one method make noise and here we have another class called dog that extends the animal class it's a sub class of animal it overrides the animal classes make noise method with its own implementation that prints out wolf wolf because it's a dog and it also has one extra method that the animal class doesn't have called growl so with these two classes upcasting would be taking a dog object and casting it as an animal type and down casting would be taking an animal object and casting it to a dog so let's start with up casting taking a dog object and casting it to an animal here's a simple example of how you could do that you can say animal my animal equals new dog if the whole concept of upcasting is new to you this might look a little weird you're probably used to seeing the same class name here as here right so here we're creating a new dog object but casting it to be an animal but you can see there's no real special extra code or anything needed to upcast an object java does all upcasting implicitly without you having to do anything since dog is a subclass of animal that means every dog is an animal so that means java has no problem at all with you doing this and you don't even need any extra casting code like putting animal here in parentheses to cast this you can add this in if you want but you don't need to java will automatically do the upcasting of dog to animal upcasting always works there are never any errors when you try to upcast an object and it always happens automatically without any special added code basically java always allows you to treat an object of a subclass type as an object of its parent type now when you do this the my animal variable here has the type of animal that's called the reference type so you can do anything with this myanimal variable that you could with any other animal variable but since it's treated as an animal variable you can't do things with this variable that only apply to dogs so remember over in our dog class we have this growl method that's only in our dog class and doesn't exist for an animal it only exists for dogs so since over here we actually have an animal object if we try to call my animal dot growl we can see that it doesn't exist we get an error the method growl is undefined for the type animal so even though underneath it's actually a dog object because the my animal variable's reference type is animal we don't have any access to any of the specific dog methods or attributes we only have what's available in animal so then you may be thinking well why do we need up casting in java what does it do for us well let me show you an example let's say we had a method like public static void do animal stuff that takes in a parameter animal we'll just call it animal and in this method we can call animal dot make noise we don't need this broken growl call anymore this method takes an animal right but when you call this method you can send an animal object but you can also send any object that's a subtype of animal it can be a dog a cat a cheetah a camel whatever this method doesn't know and doesn't really care or need to know what type of animal it's being called with it just needs to be an animal and any object that's a subtype of animal is an animal so we can call do animal stuff and pass in our my animal so let's run our program and see what we get and it prints out woof woof and that's because the my animal object that was being passed in was actually a dog and when a dog object makes noise it prints out woof woof in this case the upcasting was done right here when we initialized our animal variable to be a new dog it up casted dog to animal but even if we change this to be a dog and called it my dog and then pass that into our method you can see we still don't have any errors at all because this method is calling for an animal still any subclass of animal is totally valid to call this method with but now the implicit upcasting of dog to animal is happening when this method is being called you don't have to cast this object to an animal before calling this method remember in our animal class each animal has the ability to make noise and each subclass can override this method with their own make noise implementation if they want but what's neat is with that combination of upcasting and method overriding when this method takes its animal object and calls the make noise method on it it will make the correct noise for whichever animal object was passed in dog objects will say woof woof like we already saw and if we change this to be a cat instead of a dog and then pass in my cat we can see that it says meow so without upcasting you would have to take each and every class that you wanted to create a do animal stuff method for and make a separate do animal stuff method for each of them you'd have a separate method for cats dogs hamsters wombats and if later you added a new subclass of animal like a horse you'd have to add a whole new do animal stuff method for them with upcasting you can make one method that operates on any type of animal at all even animals that haven't been created yet one limitation of this though is because this method doesn't know which subtype of animal it's working with you can't use any of the methods that are only in those subclasses so if we change all this back to dog and then call a method with my dog remember we have a method in our dog class called growl that doesn't exist in the animal class so even though we're passing in a dog object to this do animal stuff method we can't call animal.growl so the type of the variable determines which methods you can call but the specific type of the object that this variable is referring to determines which specific implementation of that method will be used when the method is called that's why when this make noise method is called on a dog it says woof and when it's called on a cat it says meow now on to down casting remember up casting always works and always happens automatically all dogs cats and beavers are animals so java has no problem treating any of those as animals but downcasting is different it doesn't happen automatically so you have to do it explicitly and it can throw exceptions if you don't put in the right checks so you have to know what you're doing so first how do you do a downcast let's say we wanted to take our animal object here in this method and downcast it to be a dog how do we do that well all we have to do is say dog my dog equals in parentheses dog animal basically what's happening here is we're telling java hey i know all we have here is an animal variable but trust me i know that this animal is a dog so please cast it as a dog so i can treat it as one and jabba just trusts that you know what you're doing and says okay all right i'll give it a try so now since we have cast this animal to a dog we can treat this my dog variable just as we would any other dog variable so now we can call my dog.growl and if we are actually passing a dog object to our method it works great our dog is making noise with a woof woof and growling with a gur well that worked out great right no problems at all well right there's no problems if we actually are passing in a dog object but what if we aren't what if we instead pass in a cat change all this stuff to cat run our program and see what happens and well our program died and threw a class cast exception and we can see a line where it happened here line 15 we can click on it and it happened here when we were trying to cast this animal as a dog basically what happened here is we told java hey i know we could be taking any type of animal here but trust me this animal is a dog come on would i ever lie to you just go ahead and cast this animal as a dog so we can get growling and java says all right if you know it's always going to be a dog i'll trust you and go ahead and cast this as a dog but then we betrayed that trust and we sent in a cat so when you do that and java tries to cast it to a different object than it really is that's when you get a class cast exception so how can you avoid this what if you still want to be able to take in any type of animal so you can make noise with whatever type of animal is sent in but also if this animal happens to be a dog you want to be able to cast it as a dog so you can growl but you also don't want it to explode if it's not a dog so what do you do what you can do is add a special kind of check to see if this animal object that's being passed in actually is a dog it's pretty simple you can do it like this if animal instance of all one word all lowercase dog open and close your curly braces like any other if statement and then put all of this code involved with casting it as a dog and using it as a dog inside this if block so this instance of check will return true if this animal object that was passed in is actually a dog and false if it's anything else like a cat a lemur or whatever once we know that this animal object actually is a dog we can safely cast it as a dog and we can call our growl method safely and if we pass any other type of animal this instance of check returns false and we skip this whole code block and we avoid having a class cast exception so let's give it a test we're still passing in a cat last time it blew up with that exception so what happens now well all it's doing is saying meow because this make noise method is still being called a cat makes noise by saying meow so that works and since it's not a dog it skips this whole code block and if we change all this stuff back to dog it says yep you actually did pass in a dog so it casts this animal to be a dog and growls so to safely downcast you should always use this instance of check if not you risk getting a classcast exception if the object that you're working with turns out to be a different type than you thought if you enjoyed this video or learned something please let me know by hitting the like button and of course if you really want to support the channel you can do the whole youtube trifecta of leaving a like a comment and hitting the subscribe button so you don't miss each new video i really appreciate those of you who take the time to do that it's the only way these videos get out to help more people so it really means a lot thanks for watching and i'll see you next time
Info
Channel: Coding with John
Views: 84,103
Rating: undefined out of 5
Keywords: java, codingwithjohn, coding with john, java beginner lesson, upcasting and downcasting in java, upcasting in java, downcasting in java, java downcasting, java upcasting, java casting objects, java casting, java casting explained, java tutorial, java tutorial for beginners, learn java, java programming, java upcasting downcasting, java downcasting and upcasting, downcasting and upcasting in java, downcasting and upcasting java
Id: HpuH7n9VOYk
Channel Id: undefined
Length: 10min 22sec (622 seconds)
Published: Mon Oct 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.