Casting example. Need explanation! please

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

Moderator: admin

Post Reply
adrian110288
Posts: 12
Joined: Thu Aug 01, 2013 3:44 pm
Contact:

Casting example. Need explanation! please

Post by adrian110288 »

This is the code:

Code: Select all

public class CastingExample{

	public static void main(String[] args){
		
		Printable p = null;
		BlackInk black = new BlackInk();
		
		p = (Printable)black;

	}
}

class Ink {}
interface Printable{};
class ColorInk extends Ink implements Printable{}
class BlackInk extends Ink{};
I dnt understand why there is no compilation error while casting black to Printable?? Instance of BlackInk cannot be Printable because it doesnt extend Printable interface.

What am I missing here?? Please explain it to me

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

Re: Casting example. Need explanation! please

Post by admin »

It is true that an instance of BlackInk cannot be Printable because it doesnt extend Printable interface. But the variable black can point to an instance of a subclass of BlackInk and that subclass may implement Printable interface. So the compiler has no option but to allow it.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

adrian110288
Posts: 12
Joined: Thu Aug 01, 2013 3:44 pm
Contact:

Re: Casting example. Need explanation! please

Post by adrian110288 »

So from what I understand, the compiler is not concerned with the right part of the assignment is which is ' new BlackInk ()' ? It only wants to know that BlackInk black can be assigned anything?
E.g.

Code: Select all

Class NewBlackInk extends BlackInk implements Printable {}
Given that class we could create the new instance of it and assign it to black like:

Code: Select all

BlackInk black = new NewBlackInk ();


Is that what is all about?

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

Re: Casting example. Need explanation! please

Post by admin »

Yes, you got it :)
If you like our products and services, please help us by posting your review here.

adrian110288
Posts: 12
Joined: Thu Aug 01, 2013 3:44 pm
Contact:

Re: Casting example. Need explanation! please

Post by adrian110288 »

Thank you so much Paul :)

Post Reply

Who is online

Users browsing this forum: No registered users and 45 guests