public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。
public static short parseShort(String s):将字符串参数转换为对应的short基本类型。
public static int parseInt(String s):将字符串参数转换为对应的int基本类型。
public static long parseLong(String s):将字符串参数转换为对应的long基本类型。
public static float parseFloat(String s):将字符串参数转换为对应的float基本类型。
public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。
public static boolean parseBoolean(String s):将字符串参数转换为对应的boolean基本类型。
代码使用(仅以Integer类的静态方法parseXxx为例)如:
转换方式
方式一:先将字符串数字转成Integer,再调用valueOf()方法
方式二:通过Integer静态方法parseInt()进行转换
示例代码
publicclassIntegerDemo{publicstaticvoidmain(String[] args){//String --- int
String s ="100";//方式1:String --- Integer --- int
Integer i = Integer.valueOf(s);//public int intValue()int x = i.intValue();
System.out.println(x);//方式2//public static int parseInt(String s)int y = Integer.parseInt(s);
System.out.println(y);}}
publicclassPerson{publicvoideat(){
System.out.println("吃饭");}}publicclassTest{publicstaticvoidmain(String[] args){method(newPerson());
Person p =createPerson();}//引用类型作为方法参数,在前面笔记本案例中我们也使用了接口类型作为方法参数
pubic staticvoidmethod(Person p){
p.eat();}//引用类型作为返回值publicstatic Person createPerson(){returnnewPerson();}}
6.2 抽象类作为方法参数和返回值
抽象类作为形参:表示可以接收任何此抽象类的"子类对象"作为实参;
抽象类作为返回值:表示"此方法可以返回此抽象类的任何子类对象";
/* 定义一个抽象类 */publicabstractclassPerson{publicvoideat(){
System.out.println("吃饭");}publicabstractvoidwork();}/*定义子类Student*/publicclassStudentextendsPerson{publicvoidwork(){
System.out.println("学生的工作是学习...");}}publicclassTeacherextendsPerson{publicvoidwork(){
System.out.println("老师的工作是教书育人...");}}/*测试类*/publicclassTest{publicstaticvoidmain(String[] args){//1.调用method1()方法,可以传入一个Student对象,也可以传入一个Teacher对象method1(newStudent());//OK的method1(newTeacher());//OK的//2.调用method2()方法,接收的可能是Student对象,也可能是Teacher对象//所以,这里使用Person类型接收
Person p =method2();
p.work();//如果是Student对象,则调用的是Student的work();如果是Teacher对象,调用的是Teacher的work()。}//-------------------------------------------------------------------------------////抽象类Person作为形参——可以接收任何它的子类对象publicstaticvoidmethod1(Person p){
p.eat();
p.work();}//抽象类Person作为返回值——此方法可以返回一个Student对象,也可以返回一个Teacher对象publicstatic Person method2(){// return new Student();//OK的returnnewTeacher();//OK的}}
6.3 接口作为方法参数和返回值
接口作为方法的形参:【同抽象类】
接口作为方法的返回值:【同抽象类】
/*定义一个接口*/publicinterfaceUSB{publicvoidrun();}/*定义子类*/publicclassKeyboardimplementsUSB{publicvoidrun(){
System.out.println("使用键盘...");}}publicclassMouseimplementsUSB{publicvoidrun(){
System.out.println("使用鼠标...");}}/*定义测试类*/publicclassTest{publicstaticvoidmain(String[] args){//1.调用method1()方法,需要传入USB的任何子类对象都可以method1(newKeyboard());method2(newMouse());//2.调用method2()方法,此方法可能返回一个Keyboard对象,也可能返回一个Mouse对象
USB usb =method2();
usb.run();}//接口作为形参publicstaticvoidmethod1(USB usb){
usb.run();}//接口作为返回值publicstatic USB method2(){// return new Keyboard();//OK的returnnewMouse();//OK的 }}