天天看點

【泛型】泛型方法

泛型隻涉及到某個方法中的參數聲明時,使用泛型方法而不是泛型類。

定義:

不僅類可以聲明泛型,類中的方法也可以聲明僅用于自身的泛型,這種方法叫做泛型方法。泛型可用于傳回類型聲明,參數類型聲明,局部變量的類型聲明

格式:

通路修飾符<泛型清單> 傳回類型 方法名(參數清單){
    實作代碼
}
           

靜态方法:

施加類型限制的方法僞靜态方法,隻能将其定義為泛型方法,因為靜态方法不能使用期所在類的類型參數。

Code Deomo

package Genericity;

public class GenericDemo4 {

    public static void main(String[] args) {
        //定義了泛型類的執行個體gen,gen的方法就隻是使用定義的資料類型
        /*GenericClass2<String> gen=new GenericClass2<String>();
        gen.println("abc");*/
        GenericClass2 gen=new GenericClass2();
        //泛型定義在方法中,可以随意輸出指定的類型資料
        gen.println("ABC");
        gen.println();
        gen.println(true);
        gen.println(new Dog());
        gen.println(new Cat());
        GenericClass2.print("content for static method");
    }

}

class GenericClass2/*<T>*/{
    //泛型類定義的泛型會把方法引用的類型寫死
    /*public void println(T content){
        System.out.println(content);
    }
    */
    //類型的定義放在方法上
    public <T> void println(T content){
        System.out.println(content);
    }
    //泛型方法的重載
    public <T extends IAnimal> void println(T animal){
        animal.eat();
    }
    public static <T> void print(T content){
        System.out.println(content);
    }
}


interface IAnimal{
    public abstract void eat();
}

class Dog implements IAnimal{
    public void eat(){
        System.out.println("eating bones");
    }
}
class Cat implements IAnimal{
    public void eat(){
        System.out.println("eating fish");
    }
}
           

繼續閱讀