Page 1 of 1

Casting example. Need explanation! please

Posted: Thu Aug 08, 2013 6:42 pm
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

Re: Casting example. Need explanation! please

Posted: Thu Aug 08, 2013 7:13 pm
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.

Re: Casting example. Need explanation! please

Posted: Fri Aug 09, 2013 4:30 am
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?

Re: Casting example. Need explanation! please

Posted: Fri Aug 09, 2013 5:01 am
by admin
Yes, you got it :)

Re: Casting example. Need explanation! please

Posted: Fri Aug 09, 2013 5:03 am
by adrian110288
Thank you so much Paul :)