enthuware.ocajp.i.v7.2.1117

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
jojo314519
Posts: 1
Joined: Tue Sep 30, 2014 1:27 pm
Contact:

enthuware.ocajp.i.v7.2.1117

Post 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.

admin
Site Admin
Posts: 10054
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post by admin »

Please make sure you are running the code exactly as given.
If you like our products and services, please help us by posting your review here.

lostintesting
Posts: 1
Joined: Fri Nov 14, 2014 3:44 pm
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post 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.

admin
Site Admin
Posts: 10054
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post by admin »

Please observe lines marked //1 , //2, and //4.
If you like our products and services, please help us by posting your review here.

baichen7788
Posts: 23
Joined: Fri Mar 26, 2021 7:25 am
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post by baichen7788 »

I don't understand why t=(Truck)a will result in ClassCastException.

admin
Site Admin
Posts: 10054
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post by admin »

Does the variable a refer to an object of type Truck at run time?
If you like our products and services, please help us by posting your review here.

baichen7788
Posts: 23
Joined: Fri Mar 26, 2021 7:25 am
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post 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;
}

}

admin
Site Admin
Posts: 10054
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: enthuware.ocajp.i.v7.2.1117

Post 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
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 54 guests