2010-08-17 20 views
31

içinde türetilmiş sınıftan temel sınıf kurucusunu çağırmak:şöyle bir sınıf var Java

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; 
    } 
} 

Şimdi düzenli çokgen olan tüm tarafların eşit olduğu bir çokgendir. Normal poligonumun kurucusu ne olmalı?

public Regularpolygon extends Polygon{ 

//constructor ??? 
} 
+1

olmalıdır. Ama daha önce daha fazla soru sordun. Onları bulamıyorsanız, adınızın bir bağlantı olarak göründüğü herhangi bir yeri tıklayın (örneğin üst çubukta veya yukarıdaki "sorulan" kutusunda), sonra [profil sayfanıza] ineceksiniz (http: //stackoverflow.com/users/419373/akshay). Daha önce sorduğunuz sorular da dahil olmak üzere tüm geçmişinizi burada bulabilirsiniz. Not: hesabınızı kaydettirmek güzel olurdu, aksi takdirde aynı hesabı diğer bilgisayarlarda/tarayıcılarda giriş yapamazsınız. – BalusC

cevap

50
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 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)); 
    } 
} 
2

Sizin yapıcı Size bu bir kabul bu güzel

public Regularpolygon extends Polygon{ 

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

// YOUR CODE HERE 

} 

} 
+5

Temel sınıfta no-arg kurucu sağlamak için iyi kodlama pratiği olması saçmalık için -1'e sahiptim. –

1
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); 
    } 
} 
+0

Bence soru farklıydı. Bir şekilde noktayı kaçırdın. –