I will try to be short, because the question was not answered. For a detailed explanation, go through this briefing.
I will show what I'm trying to do. Something like this (outputting the input type from the constructor to use it in another getLeaderHerd method as the return type) ...:
public class ZooCage{
private CageFamily<T> inhabitants;
public <T>ZooCage(CageFamily<T> herd) {
this.inhabitants=herd;
}
public T getHerdLeader() {
return inhabitants.getLeader();
}
}
or
public class ZooCage{
private (Type) T;
public ZooCage(CageFamily<T> herd) {
this.T=T;
}
public T getHerdLeader() {
return inhabitants.getLeader();
}
}
so that I can call from Main something like:
ZooCage cage = new ZooCage(new CageFamily<Lion>()); //Imagine new CageFamily its not empty
Lion leader = cage.getHerdLeader();
Even if this is not possible, why should I think that it is impractical? Its type is safe if the compiler is intelligent and less redundant, which typifies the ZooCage class, which is not needed
I, m . , , arg. , .
( 2 )
, . :
package Zoo;
import Zoo.Main.CageFamily;
import Zoo.Main.Vertebrate;
public class ZooCage<T extends Vertebrate>{
private CageFamily<T> inhabitants;
public ZooCage(CageFamily<T> herd) {
this.inhabitants=herd;
}
public T getHerdLeader() {
return inhabitants.getLeader();
}
}
, (/ / )
, Main.java
package Zoo;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
new Main().test();
}
public void test(){
CageFamily<Lion> lionsHerd = new CageFamily<Lion>();
lionsHerd.add(new Lion("Simba"));
lionsHerd.add(new Lion("Nala"));
CageFamily<Bear> bearsHerd = new CageFamily<Bear>();
bearsHerd.add(new Bear("Yogi"));
bearsHerd.add(new Bear("Boo-boo"));
ZooCage<Lion> cageLions = new ZooCage<Lion>(lionsHerd);
ZooCage<Bear> cageBears = new ZooCage<Bear>(bearsHerd);
for (ZooCage<?> cage : new ZooCage[]{cageLions,cageBears} )
System.out.println("The leader is "+ cage.getHerdLeader());
}
public interface Vertebrate{
public String toString();
public int numBones();
}
public class Lion implements Vertebrate{
private String name;
public Lion (String name){this.name=name;}
public String toString(){return name + " (who has "+numBones()+" bones)";}
public int numBones(){return 345;}
}
public class Bear implements Vertebrate{
private String name;
public Bear (String name){this.name=name;}
public String toString(){return name + " (who has "+numBones()+" bones)";}
public int numBones(){return 658;}
}
public class CageFamily<E extends Vertebrate> extends ArrayList<E>{
final static long serialVersionUID = 1L;
public E getLeader(){
return get(0);
}
}
}
The leader is Simba (who has bones)
The leader is Yogi (who has bones)
: - ( / ), ZooCage ? ZooCage, s getHerdLeader. ZooCage, . !
, !