泛型
由于类型转换的错误,java虚拟机在编译时不会报错,而在运行时报异常。
所以安全隐患非常明显,为此我们需要泛型来弥补这一问题。
是将 泛型 固定的类的所有方法和成员全部可以显示出来,
以供程序员可以确定程序的编写是否有误的机制。
由于类型转换的错误,java虚拟机在编译时不会报错,而在运行时报异常。
所以安全隐患非常明显,为此我们需要泛型来弥补这一问题。
有了泛型,在集合类中添加对象时就不用再强转了。
import java.util.*;
public class main {
public static void main(String[] args) {
// TODO code application logic here
//通过泛型将类型定下来
ArrayList<snacks> ff=new ArrayList<snacks>();
snacks ls1=new snacks("薯片",5f);
ff.add(ls1);
//泛型保证这里强制转换类型不出错,在申请集合类之前加上<snacks>
snacks cls=(snacks)ff.get(0);
}
}
class snacks
{
private String Sname;
private float Sprice;
public snacks(String Sname, float Sprice) {
this.Sname = Sname;
this.Sprice = Sprice;
}
}
class drink
{
private String Dname;
private float Dprice;
private String Dcolor;
public drink(String Dname, float Dprice, String Dcolor) {
this.Dname = Dname;
this.Dprice = Dprice;
this.Dcolor = Dcolor;
}
}
是将 泛型 固定的类的所有方法和成员全部可以显示出来,
以供程序员可以确定程序的编写是否有误的机制。
import java.lang.reflect.Method;
import java.util.*;
public class main {
public static void main(String[] args) {
Bh <String> hw1 = new Bh<String>("货物1") ;
hw1.lxmc();
Bh <Integer> hw2 = new Bh<Integer>(123) ;
hw2.lxmc();
Bh <toy> hw3 = new Bh<toy>(new toy()) ;
hw3.lxmc();
}
}
class toy
{
public void play()
{
System.out.println("They are playing games right now!");
}
public int calculte(int a,int b)
{
return a+b;
}
}
//百货
class Bh<L>
{
private L l;
Bh(L l)
{
this.l = l;
}
//显示方法名称
public void lxmc()
{
//去类型(class)名称(name)
System.out.println("类型是"+l.getClass().getName());
//用数组来接收类中方法的数量
Method []a=l.getClass().getDeclaredMethods();
for (int i=0;i<a.length;i++)
{
System.out.println("函数名为:" +a[i].getName());
}
}
}