Page 1 of 1
enthuware.ocajp.i.v7.2.1117
Posted: Tue Sep 30, 2014 1:33 pm
by jojo314519
I ran it. It only prints:
Automobile: drive
Why does test say answer is:
It will print:
Automobile: drive
Truck: drive
Truck: drive
in that order.
Thanks.
Re: enthuware.ocajp.i.v7.2.1117
Posted: Tue Sep 30, 2014 7:21 pm
by admin
Please make sure you are running the code exactly as given.
Re: enthuware.ocajp.i.v7.2.1117
Posted: Fri Nov 14, 2014 3:51 pm
by lostintesting
no, he's right. the code is:
class Automobile{
public void drive() { System.out.println("Automobile: drive"); }
}
public class Truck extends Automobile{
public void drive() { System.out.println("Truck: drive"); }
public static void main (String args [ ]){
Automobile a = new Automobile();
Truck t = new Truck();
a.drive(); //1
there is only one line that calls the drive statement. a.drive(); there is not way to get three lines of output.
Re: enthuware.ocajp.i.v7.2.1117
Posted: Fri Nov 14, 2014 5:20 pm
by admin
Please observe lines marked //1 , //2, and //4.
Re: enthuware.ocajp.i.v7.2.1117
Posted: Sat Mar 27, 2021 4:51 am
by baichen7788
I don't understand why t=(Truck)a will result in ClassCastException.
Re: enthuware.ocajp.i.v7.2.1117
Posted: Sat Mar 27, 2021 5:02 am
by admin
Does the variable a refer to an object of type Truck at run time?
Re: enthuware.ocajp.i.v7.2.1117
Posted: Sat Mar 27, 2021 5:03 am
by baichen7788
class Automobile{
public void drive(){}
}
public class Truck extends Automobile {
public void drive(){}
public static void main(String[] args) {
Automobile a = new Automobile();
Truck t = new Truck();
t=(Truck) a;
}
}
Re: enthuware.ocajp.i.v7.2.1117
Posted: Sat Mar 27, 2021 5:41 am
by admin
So, what type of object does the variable a refer to??
a refers to an object of type Automobile. An Automobile is not a Truck. That is why CCE is thrown.
Please go through Java book to understand how casting works. Or you may also go through this tutorial:
https://www.baeldung.com/java-type-casting