泛型中使用方法错误问题

public class Co1 {

	public void print()
	{
		System.out.println("Co1");
	}
}


public class Holder3<T> {
	
	private T a;
	public Holder3(T a)
	{
		this.a = a;
	}
	public void set (T h4)
	{
		this.a = h4;
	}
	
	public T get()
	{
		a.print();  //here, why cant't i  use the method print() in class Co1
		return a;
	}
	
	public static void main (String[] args)
	{
		Holder3 h3 = new Holder3 (new Co1() );
		
		h3.get();
	}
}

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method print() is undefined for the type T

	at Holder3.get(Holder3.java:16)
	at Holder3.main(Holder3.java:25)



Topic below answered by Sunde887

Popeus' help while meant to be helpful, was incorrect. The problem is that T is not Co1, T is some type which is not known as you are writing the code. 


Assume for a moment that 'a.print()' was legal, then what would happen if I threw this wrench into the equation:

Holder3<String> stringHolder = new Holder3<String>();
stringHolder.get();

When you create a generic class you are writing for a generic type. It's not known until compilation; and furthermore you can't query the object easily to find information about the generic type(but this is off topic). When you declare and initialize the generic class, you tell it what type T represents, think for a moment of how to use classes such as ArrayList, you usually(and should always be) using generic parameters: ArrayList<String>, ArrayList<Integer>, etc.

So you can't have methods being called on the generic type unless you can ensure that any class which can be passed in as a generic argument, in fact contains the method.

If you'd like a print description, I'd suggest you supply an overloaded toString method and use System.out.println(Object o);
public class Co1{
  @Override public String toString(){
    ....
  }
}
public class Holder3<T>{
  private T a;
  
  @Override public String toString{
    return a.toString();
  }
  public T get(){
    System.out.println(this);
    return a;
  }
}

Topic below answed by Fubarable :

A solution would be to have your generic variable T be constrained to be only the Co1 class or its child classes:

class Holder3<T extends Co1> {

   private T a;

   public Holder3(T a) {
      this.a = a;
   }

   public void set(T h4) {
      this.a = h4;
   }

   public T get() {
      a.print(); 
      return a;
   }

   public static void main(String[] args) {
      Holder3 h3 = new Holder3(new Co1());

      h3.get();
   }
}

This will give all T variables access to all public Co1 methods.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值