Reputation: 5716
I have the main method written as following:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excercise.pkg5;
/**
*
* @author Azraar
*/
public class TestResizable {
public static void main(String[] args) {
Shape obj[] = new Shape[4];
obj[0] = new Circle(10);
obj[1] = new Rectangle(10, 20);
obj[2] = new ResizableCircle(10);
obj[3] = new ResizableRectangle(10, 20);
for (int i = 0; i < obj.length; i++) {
if (obj[i] instanceof ResizableCircle) {
ResizableCircle r = (ResizableCircle) obj[i];
obj[i].equals(r);
}
if (obj[i] instanceof ResizableRectangle) {
ResizableRectangle r = (ResizableRectangle) obj[i];
obj[i].equals(r);
}
System.out.println("");
System.out.print("Object is - " + obj[i].name());
System.out.print("\nObject Area is - " + obj[i].area());
System.out.print("\nObject Perimeter is - " + obj[i].perimeter());
}
}
}
i am using ResizableRectangle r = (ResizableRectangle) obj[i];
, because resizable is an implement and ResizableRectangle and ResizableCircle are extending it and overriding the method resize.
if instanceof resizbleRectange or resizableCircle.. i need to run this resize() method..
obj[i].resize(0.5)
and then it will loop out and print. but the problem is i am not getting resize method true intelisense also when i type it says cannot find sympbol...
below is the class hierarchy...
EDIT:
shape is the ROOT CLASS as you can see in the attached screenshot. i am thinking of a way to access resize method when object is an instace of ResizeableClass and ResizeableRectangle. but still unable.
Upvotes: 0
Views: 577
Reputation: 5716
This worked at last...
if (obj[i] instanceof ResizableCircle) {
Resizable c = (ResizableCircle) obj[i];
c.resize(5);
}
if (obj[i] instanceof ResizableRectangle) {
Resizable r = (ResizableRectangle) obj[i];
r.resize(10);
}
Upvotes: 0
Reputation: 68935
Not all subclasses of Shape method implement Resizable interface. So you need to check if obj[i]
is instance of Resizeable class and then call resize on it.
Upvotes: 1
Reputation: 16526
You declared obj
as
Shape obj[]
so obj[i]
will return a Shape
object which I'm guessing doesn't extend Resizeable
.
Upvotes: 1
Reputation: 272277
You need to call resize()
on a Resizeable
reference.
That is, if obj[i]
is a Resizeable
, then you need to cast and then call it. It's not enough simply to assert that obj[i]
refers to such an object since the compiler is simply treating it as a base class reference.
e.g.
if (obj[i] instanceof Resizeable) {
((Resizeable)obj[i]).resize(..);
}
Upvotes: 2