user119016
user119016

Reputation: 11

Implement interface with generic types

I have the following interface:

interface Parcel <VolumeType, WeightType> {
    public VolumeType getVolume();
    public WeightType getWeight();
}

I want to define a class A which implements this Parcel such that the volume and weight returned from this class have type Double, and the following codes stand

Parcel<Double,Double> m = new A(1.0,2.0);
m.getVolume().toString()+m.getWeight().toString().equals("1.02.0");

I am new to generics and all my trials for the definition of A failed. Can someone please show me an example about how to define such a class?

I have tried the following:

class A implements Parcel<Double, Double> {}

The error was

Constructor A in class A cannot be applied to given types;
        Parcel<Double,Double> m = new A(1.0,2.0);
                                  ^
  required: no arguments
  found: double,double
  reason: actual and formal argument lists differ in length
2 errors

Upvotes: 1

Views: 55

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

You've added the correct implements clause. The error you're getting is that you have not defined a two-argument constructor:

class A implements Parcel<Double, Double> {
    public A(double volume, double weight) {
        ...
    }

You'll also need to implement the two interface methods:

    public Double getVolume() {
        ...
    }

    public Double getWeight() {
        ...
    }
}

Upvotes: 1

Related Questions