Search code examples
javainheritanceconstructorsubclasssuperclass

Java - Passing an object as a parameter in a constructor... from a superclass


I have these classes: an abstract class called "Shape", a class Point extends Shape, and a class Circle extends Point

I can't change this relationship. What I need to do is create a constructor in Circle which receives as parameters an object Point and a double. I already created an object Point, called point I already tried this:

public Circle (Point objPunto, double valorRadio){   
  Pointp = new Point(objPunto.getX(), objPunto.getY());
  setRadio(valorRadio);}

and

Circulo circulo2 = new Circulo(point, 3);

but it doesn't seem to work.It shows me this: Implicit super constructor Punto() is undefined. Must explicitly invoke another constructor.

I also tried some weird things using Super, but that didn't work either. I'm starting to think that it can be done, and if so... anyone knows why?

Thanks!

Code for Point

    public class Point extends Shape {

   private int x;  
   private int y;  

   public Point( int valorX, int valorY ){
      x = valorX;  
      y = valorY;  
   } 

   public void setX( int valorX ){
      x = valorX;  
   } 

   public int getX(){
      return x;
   } 

   public void setY( int valorY ){
      y = valorY;  
   } 

   public int getY(){
      return y;
   } 

   public String getName(){
      return "Punto";
   } 

   public String describe(){
      return "[" + obtenerX() + ", " + obtenerY() + "]";
   } 
} 

Solution

  • I think you can just call super() for first two arguments as below:

        public Circle (Point objPunto, double valorRadio){   
          super(objPunto.getX(), objPunto.getY());
          setRadio(valorRadio);
        }
    

    super() calls the constructor of the parent class and it should be the first statement inside the child constructor, if used.