我自己也想到另外一种方法是可以写一个工具类,如common,然后把你的print方法放到里面,这个方式同calix说的前面方法是一样的,但我想的方法后面就同calix说的后面有些不同了,我的方法是我在有main方法的类中继承common类,那么在这个类中直接调用方法就可以了,就像以下两个程序:
首先是common类:
package javatest1;
public class common {
public static <E> void print(E value)
{
System.out.println(value);
}
}
然后是继承common类有main方法的主类:
package javatest1;
public class javatest1 extends common{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
print("Hello World!");
print(100);
print(0b100);
print(0100);
print(0x100);
print(true);
print(false);
print(null);
}
}
我主要是想是定义一个通用的类放一些通用的方法如System.out.println("Hello World");和System.out.println("This is a java program");类似的输出语句每次想输出一句语句都要写System.out.println这句有点麻烦,我想一次性定义一个通用的函数如print把每次输出语句的工作量减少,就想到以上的程序,还要一个问题我想问:上面的common类中public static <E> void print(E value)(即print函数的定义),我明白参数value前面中的E是泛型(即调用这个函数的语句在传入参数任意类型都可以),但void前面的<E>自己觉得是多余的,但把void前面的<E>删除程序就报
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
The method print(E) from the type common refers to the missing type E
at javatest1.javatest1.main(javatest1.java:10)
这个错误,那么void前面的<E>起的作用是什么?