Java——数据类型的转换及instanceof

  1. 基本数据类型的转换
    (1)自动类型转换
    byte->short->char->int->long->float->double
    byte,short,char进行算数运算时会自动转换成int
    boolean类型不参与数据类型转换
    (2)强制类型转换
    double->float->long->int->char->short->byte

  2. 引用数据类型的转换
    父子类之间的转换
    (1)向上转型:把子类的对象赋值给父类的变量
    目的:方便统一管理各子类的对象
    (2)向下转型:把父类的变量赋值给子类的变量
    目的:为了调用子类特有的方法
    向下转型成功的条件:必须之前是向上转型,并且保证改变量中保存的对象的运行时类型<=强转的类型
    例如:people a =new chinesewoman(); //向上转型
    woman b=(woman)a; //向下转型(其中父子类关系:people->woman->chinesewoman,变量a中保存的对象的运行时类型chinesewoman<=强转的类型woman)
    (3)变量/对象 instanceof 类型:结果为布尔类型;
    向下转型可能发生ClassCastException 异常,我们想通过代码去避免是,可使用instanceof来判断

    public class TestInstanceof{
    	public static void main(String[] args){
    		Man m=new Man();
    		test(m);
    		Woman w = new Woman();
    		test(w);
    	}
    	public static void test(people p){
    		if(p instanceof Waman){  //**当p中存储的是Woman对象或是Woman子类的对象时,才能返回true**
    			Woman w=(Woman) p;
    			...
    		}else if(p instanceof Man){
    			Man m=(Man) p;
    			...
    		}
    	}
    }
    class People{
    	public void shop(){
    	...
    	}
    }
    class Man extends People{
    	public void shop(){
    	...
    	}
    	...
    }
    class Woman extends People{
    	public void shop(){
    	...
    	}
    	...
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值