#generic type constructor method
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
before u can use a generic u must introduce/define it
that is done either on class level or on method level
ok
wait so this doesnt work?
Can you share the full code instead of just that one part
public class Point {
public double x;
public double y;
public Point(){
x = 0;
y = 0;
}
public Point(double x, double y){
this.x = x;
this.y = y;
}
public String toString(){
Double X = x;
Double Y = y;
return "(" + X.toString() + "," + Y.toString() + ")";
}
public void print(){
System.out.print(this.toString());
}
public static void main(String[] args) {
Point a = new Point(3,2);
a.print();
}
}``` i ended up ditching generics because i couldnt cast an Integer to a Double
Detected code, here are some useful tools:
And constructors are going to be different than other methods
Yeah that's probably the right call.
so i'm letting implicit conversion do its thing
You can definitely do this with generics, but you need to make the class itself generic too and to make that function properly you'll need to make some unifying abstraction over ints and doubles which doesn't always exist
and which is way beyond me anyways lol
You can make a generic pair class
probably way beyond what i'll even touch on this semester
That's easier - but it only makes sense if you don't need to do any common operations on the actual thing within the pair
this is where operator overloading would be great so i could add points with + and do 2D vector arithmetic without calling extremely verbose methods
Well operator overloading is only one part of that
Even before you make it so that the plus sign magically calls a method you need to define that method
And that's the part where we're having a bit of an issue
Because what the heck do you do to define Point<T> add(Point<T> a, Point<T> b)
i see
Operator overloading is finally on the table in one way or another, but you'll still have this problem
Sound like a very bad idea
you can technically do it tho
with Number or BigDecimal and/or some cursed code