基本数据类型和类类型传值的区别

基本数据类型知识传值,在方法中被改变不会影响方法外边的数值。 类类型是引用,是地址的指向,当一个类被当做参数传到方法中,该参数和这个类指向同一个地址,也就是相同的引用,类的属性发生变化,方法外边的类的属性也同样会发生变化。 但是如果类类型作为参数传到方法里,而方法将参数指向另一个地址,方法外边的类的指向不会发生变化。

public  class  yinyong {
     
            
         String name;  //姓名
            
         float  hp;  //血量
            
         float  armor;  //护甲
            
         int  moveSpeed;  //移动速度
         
         public  yinyong(){
             
         }
         
         public  yinyong(String name, float  hp){
             this .name = name;
             this .hp = hp;
         }
 
         //复活
         public  void  revive(yinyong h){
             h =  new  yinyong( "提莫" , 383 );
         }
 
         public  static  void  main(String[] args) {
             yinyong teemo =   new  yinyong( "提莫" , 383 );
             
             //受到400伤害,挂了
             teemo.hp = teemo.hp -  400 ;
             
             teemo.revive(teemo);
             
              System.out.println(teemo.hp);
             
         }
          
     
}

//打印出是-17





猜你喜欢

转载自blog.csdn.net/weixin_42030389/article/details/80584282