Learn Java Tutorial for Beginners, Part 29: Upcasting and Downcasting

More courses! Free C++ course:
Make a social network with Spring Boot:
Learn about MySQL and relational databases:
Java desktop programming:…

Similar Posts

34 thoughts on “Learn Java Tutorial for Beginners, Part 29: Upcasting and Downcasting
  1. Most people learning Java, or C# for that matter, will never do C++. So for them, it probably doesn't make too much difference whether you say variable or reference. But even there, in C#, as there is a big distinction between value types and reference types, I would prefer saying reference rather than variable. Here in the land of Java, it is probably fine to say variable rather than reference 99% of the time, but I think many people who are multi-lingual would gravitate to saying reference, since in both C# and C++ you can actually have variables (rather than references) of complex types, and it leaves no ambiguity. I do see a handful of confused people in the comments that perhaps would be less confused if we said reference everywhere. In C++ if you pass a subclass by value as a superclass, you actually get object slicing (OUCH!!), so it is of paramount importance to keep them clear. Many people watching these videos are going to be using only Java, so it is just a little thing I am pointing out, rather than some stark criticism or complaint.

  2. Would you guys tend to agree then, that it's correct to say in order to downcast your first will have to upcast, as following:

    //First the upcast needs to take place
    ParentClass parentObject = new ChildClass();

    //THEN, once the upcasting above is done we can downcast to render access of the //parentObject's implementations of the ChildClass's methods
    ChildClass childObject = (ChildClass) parentObject;

    //Notice we could NOT have done the directly-above downcasting had we NOT first had an object that was upcasted from type of parent to refer to object of child, I suppose downcast cannot exist without upcast?

  3. Why do i get an error???

    See code below.

    class Machine {
    public void start() {
    System.out.println("Mac start");
    class Camera {
    public void start() {
    System.out.println("Camera start");
    public void snap() {
    System.out.println("Camera take pic");
    public class App2 {
    public static void main(String[] args) {

    Machine mac1 = new Machine();
    Camera cam1 = new Camera();


    // Upcasteing
    Machine mac2 = cam1; (on this line it says "Cant convert Camera to Machine")
    mac2.start(); ( It alows me to call mac2.start(); with no error)

Leave a Reply

Your email address will not be published. Required fields are marked *