用类来生成对象的语句

用类来生成对象的语句:

Student  s=new Student()。

第一个Student表示这是用Student类进行定义。“Student()”表示调用一个无参数的构造方法。

如果()中有参数,则系统构造对象的过程中调用有参的方法。

此时S称为一个对象变量。

 Student s的存储区域存放的是地址:一个对象在硬盘上占有一个连续地址,首地址赋予s空间。

S称为对象Student的引用。

注意:在对象变量中存放的是引用(地址);在简单变量中存放的是数值。

 1 package TomText;
 2 
 3 public class TomText_07 {
 4     /*
 5       * 求n之前的奇数的和
 6       */
 7      public int sumOfOdd(int n){
 8       
 9       int j = 0;   //奇数
10       int sum = 0; //n之前的奇数的和
11       int m = (n+1)/2; //n之前的奇数的个数
12       
13       for(int i=0;i<m;i++){
14        
15        j = 2*i+1;  //第i+1个奇数的值,i初始为0
16        sum += j;   //计算n之前的奇数的和
17       }
18       return sum;
19      }
20      public static void main(String[] args) {
21          TomText_07 t=new TomText_07();
22          int n=t.sumOfOdd(4);
23          System.out.println(n);
24      }
25 }

猜你喜欢

转载自www.cnblogs.com/borter/p/9418513.html
今日推荐