parent type and object as child

gudii9
gudii9 used Ask the Experts™
on
One interesting point with inheritance in Java is that, we can use the super type when creating a new object of the sub type.
Suppose Car is the parent class of the Truck class as shown in the following code:
1
2
3
4
5
6
7
8
9
public class Car {
    public void move() {
    }
}
 
public class Truck extends Car {
    public void load() {
    }
}
It’s legal to write:
1
Car vehicle = new Truck();
The rule is: the type on the left side can be super type of the actual object in the right side. Note that the only methods we can invoke are the ones declared in the super type, for example:
1
vehicle.move(); //okay, since Truck inherits Car
Also note that, if the subclass declares a new method, we cannot invoke it using the super type reference:
1
vehicle.load(); // compile error

Open in new window


IF i take parent type and object as child i am getting error.

but when i cast it as below no error

can you please advise why no error

package ParentSuperTypeObjectSubType;

public class TestClass {
	public static void main(String[] args) {
		Car vehicle = new Truck();
		vehicle.move(); //okay, since Truck inherits Car
		vehicle.load(); // compile error
		((Truck) vehicle).load(); // ok
	}

}

Open in new window


below also worked fine if i cast
package ParentSuperTypeObjectSubType;

public class TestClass {
      public static void main(String[] args) {
            Car vehicle = new Truck();
            Truck car = new Car();  // Compile error
            Truck car = (Truck) new Car();  // Compile error
            vehicle.move(); //okay, since Truck inherits Car
            vehicle.load(); // compile error
            ((Truck) vehicle).load(); // ok
      }

}



is above is upcast or downcast
i confuse those similar name?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2018
Commented:
The method load() is only available to the child class, therefore you cannot call it from the parent class.

This

 ((Truck) vehicle).load(); // ok

Open in new window


is down-casting (you cast to a subtype).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial