How can I access my secondary interface method in my for loop?
I can't access my el.print() in my for loop. These are four different files. I have two interfaces with separate names. I can't combine them or add or remove and new methods. I can change current methods however. There are similar classes as to triangle for square, rectangle, etc. Circle cannot access Printable.print, the other three can.
Code java:
public class InterfaceApp
{
public static void main( String[] args )
{
Rectangle myRectangle = new Rectangle( 6, 3 );
Square mySquare = new Square( 5, 5 );
Triangle myTriangle = new Triangle( 6 );
Circle myCircle = new Circle( 5 );
System.out.println( myRectangle );
System.out.println();
System.out.println( mySquare );
System.out.println();
System.out.println( myTriangle );
System.out.println();
System.out.printf( myCircle + "%nDiameter: %d%nCircumference: %.1f%n%n",
myCircle.diameter(), myCircle.circumference() );
System.out.printf( "Shape Array: %n-----------%n" );
Shape[] myShapes = { mySquare, myRectangle, myTriangle, myCircle };
mySquare.print();
myRectangle.print();
myTriangle.print();
for ( Shape el : myShapes )
{
System.out.printf( el + "%nPerimeter: %.1f%nArea: %.1f%n",
el.perimeter(), el.area() );
if (!( el instanceof Circle ))
{
el.print();
}
}
}
}
public class Triangle implements Shape, Printable
{
private final int leg;
private final double hypotenuse;
public Triangle( int l )
{
leg = l;
hypotenuse = leg*Math.sqrt( 2.0 );
}
public int getLeg()
{
return leg;
}
public double getHypotenuse()
{
return hypotenuse;
}
@Override
public String toString()
{
return String.format( "Triangle(%d)", leg );
}
@Override
public double perimeter()
{
return 2*leg + hypotenuse;
}
@Override
public double area()
{
return .5*(Math.pow( leg, 2 ));
}
@Override
public void print()
{
String gap = "";
System.out.println( "* " );
for ( int i = 1; i < leg; i++ )
{
if ( i == leg - 1 )
{
for ( int j = 0; j < leg; j++ )
{
if ( j == leg - 1 )
{
System.out.println( "* ");
}
else
{
System.out.printf( "* " );
}
}
}
else
{
if ( i == 1 )
{
gap = "";
}
else
{
gap += " ";
}
System.out.println( "* " + gap + "* " );
}
}
}
}
public interface Shape
{
double perimeter();
double area();
}
public interface Printable
{
void print();
}
Re: How can I access my secondary interface method in my for loop?
It could be because im tired but i dont see where el is declared.
Re: How can I access my secondary interface method in my for loop?
If there are error messages, copy the full text of the messages and paste it here.
The Shape interface does not have a print() method.
The Printable interface does have a print() method. Make el a Printable.
Re: How can I access my secondary interface method in my for loop?
I just extended Shapes with Printable. Problem solved.