37

I have a class as follows:

public class Polygon  extends Shape{

    private int noSides;
    private int lenghts[];

    public Polygon(int id,Point center,int noSides,int lengths[]) {
        super(id, center);
        this.noSides = noSides;
        this.lenghts = lengths;
    }
}

Now a regular polygon is a polygon whose all sides are equal. What should be the constructor of my regular polygon?

public Regularpolygon extends Polygon{

//constructor ???
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
akshay
  • 551
  • 2
  • 5
  • 9
  • 2
    It's nice that you accepted this one. But you've asked more questions previously. If you can't seem to find them, just click anywhere your name appears as a link (e.g. in top bar or in the `asked` box right here above), then you'll land in your [profile page](http://stackoverflow.com/users/419373/akshay). You can find all your history there, including questions you asked before. PS: registering your account would be nice, else you won't be able to login the same account at other PC's/browsers. – BalusC Aug 17 '10 at 17:51

3 Answers3

58
public class Polygon  extends Shape {    
    private int noSides;
    private int lenghts[];

    public Polygon(int id,Point center,int noSides,int lengths[]) {
        super(id, center);
        this.noSides = noSides;
        this.lenghts = lengths;
    }
}

public class RegularPolygon extends Polygon {
    private static int[] getFilledArray(int noSides, int length) {
        int[] a = new int[noSides];
        java.util.Arrays.fill(a, length);
        return a;
    }

    public RegularPolygon(int id, Point center, int noSides, int length) {
        super(id, center, noSides, getFilledArray(noSides, length));
    }
}
Community
  • 1
  • 1
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
3
class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}
skuntsel
  • 11,624
  • 11
  • 44
  • 67
2

Your constructor should be

public Regularpolygon extends Polygon{

public Regularpolygon (int id,Point center,int noSides,int lengths[]){
super(id, center,noSides,lengths[]);

// YOUR CODE HERE

}

}
JWhiz
  • 681
  • 3
  • 10
  • 22
  • 5
    I had to -1 for the nonsense about it being good coding practice to provide a no-arg constructor in the base class. – Mark Peters Aug 17 '10 at 17:39