gutenmorgenuhu
gutenmorgenuhu

Reputation: 2362

Call SuperConstructor from secondary constructor

I have the class Circle which extends CanvasElement. I want to be able to create a circle just by giving a radius AND by initializing with the total set of values. At the moment, my code looks clunky, setting each value from the super class one by one. How can I just call the super constructs with all values (posX, posY, etc. passed into the constructor call?

class Circle(var radius : Double = 0.0) : CanvasElement(){
constructor(posX : Double,
        posY : Double,
        radius : Double,
        fill : String,
        stroke : String) : this(radius){
    this.fill = fill
    this.stroke = stroke 

    this.posX = posX
    this.posY = posY
}

Class: CanvasElement

open class CanvasElement(
    var posX : Double = 0.0,
    var posY: Double = 0.0,
    var fill : String = "",
    var stroke : String = ""){
}

For a better understanding, I have added the java code for what I want to achieve:

Circle

public class Circle extends CanvasElement{
    private int radius;

    public Circle(int radius){
        super(0,0);
        this.radius = radius;
    }
}

CanvasElement

public class CanvasElement{
    private double posX;
    private double posY;

    public CanvasElement(double posX, double posY){
        this.posX = posX;
        this.posY = posY;
    }
}

Upvotes: 0

Views: 51

Answers (2)

DVarga
DVarga

Reputation: 21799

Do you would like to have something like this?

open class CanvasElement(var posX: Double , var posY: Double, var fill: String , var stroke: String)

class Circle(var radius: Double = 0.0,
             posX: Double = 0.0,
             posY: Double = 0.0,
             fill: String = "",
             stroke: String = "") : CanvasElement(posX, posY, fill, stroke)

IF I understood you properly you don't want CanvasElement to have deafults and you want to be able to create a Circle by defining only the radius and possibly other properties that CanvasElement has.

Upvotes: 1

madhead
madhead

Reputation: 33412

Why not use the defaults like you did in CanvasElement?:

class Circle(
    var radius : Double = 0.0,
    var posX : Double = 0.0,
    var posY: Double = 0.0,
    var fill : String = "",
    var stroke : String = ""
) : CanvasElement(posX, posY, fill, stroke)

This declaration will allow to pass any number of the parameters:

Circle() // Circle(radius = 0.0) + CanvasElement(0.0, 0.0, "", "")
Circle(10.0) // Circle(radius = 10.0) + CanvasElement(0.0, 0.0, "", "")
Circle(10.0, 1.0, 2.0, "red", "black") // Circle(radius = 10.0) + CanvasElement(1.0, 2.0, "red", "black")

Upvotes: 1

Related Questions