控制程序流程&初始化

来源:互联网 发布:c语言精彩编程百例 编辑:程序博客网 时间:2024/05/20 01:47


1) java 没有sizeof()。所有数据类型在所有机器中的大小都相同!

2)对于构造函数的参数,如果数据类型(实际参数类型)“小于”方法中声明的形式参数类型,实际数据类型就会被“提升”。char型略有不同,如果无法找到恰好接受char参数的方法,就会把char直接提升到int型。如果“大于”方法中声明的形式参数类型,就需要进行“转换”,否则报错!

3) this 的使用:

public class Flower{

  static Test monitor = new Test();

  int petalCount = 0;

  String s = new String("null");

  Flower(int petals){

    petalCount = petals;

    System.out.println(

      "Constructor w/ int arg only, petalCount=" + petalCount);

  }

  Flower(String ss){

    System.out.println(

      "Constructor w/ String arg only, s=" +ss);

    s = ss;

  }

  Flower(String s, int petals){

    this(petals);

//!  this(s); //Can't call two!

    this.s = s; //Another use of "this"

    System.out.println("String & int args");

  }

  Flower(){

    this("hi", 47);

    System.out.println("default constructor (no args)");

  }

  void print(){

//!this(11); // Not inside non-constructor!

    System.out.println("petalCount = "+ petalCount + "s = " + s);

  }

  public static void main(String[] args){

    Flower x = new Flower();

    x.print();

   ......

  }

}

    构造器Flower(String s,int petals)声明:尽管可以用this调用一个构造器,但却不能调用2个。构造器(构造函数)必须置于最起始处,否则编译器会报错。

    this解决了参数s的名称和数据成员s的名字相同的问题。

    print()方法表明,除构造器以外,编译器机制在其他任何方法中调用构造器。

4) static的含义

    在static方法的内部不能调用非静态方法(这不是完全不可能的,如果把某个对象的引用传递到static方法里,然后通过这个应用(和this效果相同),就可以调用非静态方法和非静态数据成员。但通常要达到这样的效果,只需写一个非静态的方法就可以),反过来倒是可以。通过static可以不创建对象就可以使用静态方法,相当于全局函数。

原创粉丝点击