注册 登录
编程论坛 JAVA论坛

关于setInfo()的问题

bjut_Allen 发布于 2017-03-11 13:20, 2052 次点击
问题在注释处
程序代码:
public class Score {
      private int No;
      private int score;
       public Score(){   
           No=1000;
           score=0;
       }
      
       public Score(int n,int s){   
           this.No=n;
           this.score=s;
           
       }
      
    public void setInfo(int n,int s){   //这个方法有什么用呢,我前面写的构造方法和这个效果是一样的吧
           No=n;
           score=s;
           }
      
       public int getNo(){
          return No;
       }
       public int getScore(){
           return score;
        }
}

public class ScoreTest {
      public static void main(String[] args){
          Score [] student=new Score[10];
          for(int i=0;i<10;i++){
              student[i]=new Score(1000+i,(int)(Math.random()*100));
          }
          for(int i=0;i<10;i++){
              System.out.println(student[i].getNo()+"\t"+student[i].getScore());
          }
      }
}

2 回复
#2
梦月神游2017-03-11 19:28
回复楼主:不一样!

程序代码:
     public Score(int n,int s){   
           this.No=n;
           this.score=s;
           
       }


  public void setInfo(int n,int s){   //这个方法有什么用呢,我前面写的构造方法和这个效果是一样的吧
           No=n;
           score=s;
           }


前者是用于创建对象的构造方法,后者是在创建对象完毕的时候使用的类方法。
前者是通过new构造的,后者是引用new出来的类方法。
每次使用前者都会分配一个新的空间。但每次使用后者是属于方法重载,是在new里面的类里面执行的,不会另外分配空间。

形象一点的就是前者在架构房子,后者在房子里面工作。只不过这个程序在架构房子的同时和在房子里面工作的内容是一样的,但要先有房子才能在房子里面工作。
#3
bjut_Allen2017-03-12 13:43
回复 2楼 梦月神游
您回答的太细致了!懂了
1