简体   繁体   中英

Calling parameterized constructor of super class with different datatype in java?

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public abstract class Polygon {
    private List<Double> sides;
    
    public Polygon(List<Double> sides)
    {
        this.sides=sides;
    }

    public List<Double> getSides() {
        return sides;
    }
    
}

public class Square extends Polygon{
    public Square(Double side1) {
        // here i want to call super(sides). how do i convert double(side1) to list. 
    }
}

I want to call the constructor of polygon class from square class but how do i convert double to list?

Note : I cannot change any datatype.

You can create a list with that one double repeated four times:

super(Arrays.asList(side1, side1, side1, side1));  //java 8
super(List.of(side1, side1, side1, side1));        //java 9+

The below code, will convert your double to a list, which can be used as a parameter to invoke the constructor.

DoubleStream.of(doublesArray).boxed().collect(Collectors.toCollection(ArrayList::new)); 

doublesArray is the Double param

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM