Hi, I just launched Java for a course that I will be taking soon (yes, I'm a nerd, I study before I start this class). I wanted to combine several concepts to find out how everything works in Java.
Now what I wanted to try to do was a simple Shape class (Forme in french), which has a minimum of 1-2 classes inheriting from it and makes several instances inside the collection object. I also wanted to make these classes generic in order to try this. This is the part that I'm having problems with.
I am very used to C ++, so this may be a confusing problem, but it seems that I cannot use generics so that, for example, I can indicate that the measurements will be, say, integer or double or Float or whatever. Is it possible?
The GetArea () method below cannot compile due to base and hauteur .
package testconcepts; import java.util.*; import java.lang.*; abstract class Forme <T extends Number> { protected String nom_forme; String NomForme() { return nom_forme; } abstract Double GetArea(); } class Triangle <T extends Number> extends Forme { protected T base, hauteur; Triangle() { this.nom_forme = "TRIANGLE"; } @Override Double GetArea() { return base * hauteur / 2; } T GetBase() { return base; } T GetHauteur() { return hauteur; } void SetBase(T base) { this.base = base; } void SetHauteur(T hauteur) { this.hauteur = hauteur; } } public class TestConceptsJava { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(new Triangle<Double>()); } }
Please note that I also cannot assign 0 in the constructor due to type problems.
In addition, I know that there are very similar topics, but I have not yet found a solution to my problem in these other issues.
TL; DR How can I create generics for working with primitives of a primitive type (Double, Integer ..)?
source share