importstaticjava.lang.Math.*;publicclassTest{publicstaticvoidmain(String[] args){double x =30;double y =40;// 静态导入的方式写起来更方便一些.// double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));//使用import导包代码double result =sqrt(pow(x,2)+pow(y,2));System.out.println(result);}}
classStudent{//实例成员变量privateString name;privateString gender;privateint age;privatedouble score;publicStudent(){System.out.println("I am Student init()!");}//实例代码块{this.name ="bit";this.age =12;this.sex ="man";System.out.println("I am instance init()!");}publicvoidshow(){System.out.println("name: "+name+" age: "+age+" sex: "+sex);}}publicclassMain{publicstaticvoidmain(String[] args){Student stu =newStudent();
stu.show();}}/* 运行结果
I am instance init()!
I am Student init()!
name: bit age: 12 sex: man
*/
3.4使用static定义的代码块称为静态代码块。一般用于初始化静态成员变量。
publicclassStudent{privateString name;privateString gender;privateint age;privatedouble score;privatestaticString classRoom;//实例代码块{this.name ="bit";this.age =12;this.gender ="man";System.out.println("I am instance init()!");}// 静态代码块static{
classRoom ="bit306";System.out.println("I am static init()!");}publicStudent(){System.out.println("I am Student init()!");}publicstaticvoidmain(String[] args){Student s1 =newStudent();Student s2 =newStudent();}}
注意事项
1.静态代码块不管生成多少个对象,其只会执行一次
2.静态成员变量是类的属性,因此是在JVM加载类时开辟空间并初始化的
3. 如果一个类中包含多个静态代码块,在编译代码时,编译器会按照定义的先后次序依次执行(合并)
4.实例代码块只有在创建对象时才会执行
4.对象的打印
重写toString方法
publicclassPerson{String name;String gender;int age;publicPerson(String name,String gender,int age){this.name = name;this.gender = gender;this.age = age;}@OverridepublicStringtoString(){return"["+ name +","+ gender +","+ age +"]";}publicstaticvoidmain(String[] args){Person person =newPerson("Jim","男",18);System.out.println(person);// 输出结果:[Jim,男,18]}}