Would the following work?
item1.display() ;
No. All the compiler has been told is that item1
implements the
methods in the interface Taxable
.
The display()
method is not in the interface.
public class Store
{
public static void main ( String[] args )
{
Taxable item1 = new Book ( "Emma", 24.95, "Austen" );
System.out.println( "Tax on item 1 "+ item1.calculateTax() );
((Book)item1).display();
}
}
When you use a variable of type Taxable
you are asking to use the "taxable" aspect of the object.
Many different kinds of objects might be referred to by the variable.
In a larger program there may be Taxable
classes that are not Goods
.
The compiler can only use the methods associated by the type of the reference variable.
In the program, only the calculateTax()
method is associated with the reference variable.
However, a type cast
tells the compiler that
a particular variable refers to an object of a specific class:
((Book)item1).display();
Now the display()
method of the object pointed to by item1
is invoked because
the compiler has been told that item1
points to a Book
.
This program is not very sensibly written.
If the variable item1
always points to a Book
it would be more sensible to make it of type Book
.
But programs with complicated logic sometimes need such casts.
Why are the red parentheses needed in:
((Book)item1).display();