Chris Rubio1,643 Points
Can someone please give me a different example of casting without using treet.?
the whole object obj = treet; is so confusing , can someone please try to give me a different example with different variable names .
Allan Clark10,805 Points
Essentially this is talking about the practical use of inheritance/object hierarchy. He is using Object because in Java everything (thats not a primitive type) is a Object at its root.
For example, suppose we have an application for tracking automobiles. We could have a Car class, a Truck class, and a Motorcycle class. They will all have characteristics in common so we can have them all inherit from an Automobile class.
What this video is showing you is how the types of variables behave when dealing with an object hierarchy like this. In this example any Car object can be held in a variable of type Car or of type Automobile, but the variables and methods that are specific to the Car class can't be accessed if the variable is Automobile type and would require a down cast.
Car mazda = new Car(); mazda.getTrunkSpace(); //this will work because the variable is a car Automobile auto = mazda; auto.getTrunkSpace(); //this will error because not all automobiles have trunks Car sameCar = (Car) auto; sameCar.getTrunkSpace(); //works again bc we downcast
excuse my rusty java syntax lol. hope this helps