I need to write a java method to get specific information from an object. However, the object can either be of type A or of type B. Here is the part of my code :
class Composant{
int quantité;
static Composee pieceCompo;
static Simple pieceSimp;
public Composant(Composee piece, int nombre){
pieceCompo = piece;
quantité = nombre;
}
public Composant(Simple piece, int nombre){
pieceSimp = piece;
quantité = nombre;
}
public Composee getPiece(){
return pieceCompo;
}
public Simple getPiece(){
return pieceSimp;
}
public int getQuantite(){
return quantité;
}}
When I write it like that it raises an error saying "Duplicate method". How can I get this to work?
CodePudding user response:
As per JLS, §8.4.2:
...
The signature of a method
m1is a subsignature of the signature of a methodm2if either:
m2has the same signature asm1, or- the signature of
m1is the same as the erasure (§4.6) of the signature ofm2.Two method signatures
m1andm2are override-equivalent iff eitherm1is a subsignature ofm2orm2is a subsignature ofm1.It is a compile-time error to declare two methods with override-equivalent signatures in a class.
...
This means that methods public Composee getPiece() and Simple getPiece() are override-equivalent. Since those two methods are in the same class, the compiler generates a compile-time error.
As was pointed out by azro in the comments, we can instead write two separate getters Composee getComposee() and Simple getSimple().
If Simple and Composee have a common supertype (e.g. Piece), we can return write a Piece getPiece() instead.
CodePudding user response:
Try this maybe:
public class Composant<T>{
private final int quantite;
private final T comp;
public Composant(T comp,int quantite) throws BadTypeException {
if(!(comp instanceof Composee) || !(comp instanceof Simple)) throw new BadTypeException("Can't create Composant with \"" comp.getClass().getName() "\" type object!");
this.comp = comp;
this.quantite = quantite;
}
public T getPiece(){
return this.comp;
}
public int getQuantite(){
return this.quantite;
}
}
Exception is:
// If you don't want to catch exception, change it to "RuntimeException"
class BadTypeException extends Exception{
public BadTypeException(String message){
super(message);
}
}
And create like this:
try {
new Composant<Composee>(new Composee(),4);
} catch (BadTypeException e) {
e.printStackTrace();
}
