1.对于导入的包来说,调用静态方法应该有用 类名.方法名,调用非静态方法,应该用 类名.class.newInstance().方法名调用
2.使用类名.class.newInstance()真的会创建一个对象,如果该类有静态的id值,创建一个新对象增加这个值,那么通过这个方法创建的对象会增加这个id值。
3.一个类中可以有其他的类,其他类也可以和主类一样有main方法,常被用来做单元测试。
4.静态数据域又被称为是类域,所有类中的元素可以共享。那么静态方法就被称为是类方法,对象虽然也可以调用,但是不推荐。下面是实验的代码
package chapter4;
import java.time.LocalDate;
import chapter4.OtherClass;
public class TestStatic {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
System.out.println(OtherClass.getnum());
OtherClass.staticmethod();;
OtherClass.class.newInstance().notstaticmethod();;
System.out.println(OtherClass.getnum());
myEmployee[] staff = new myEmployee[2];
System.out.println();
staff[0] = new myEmployee("duan ",LocalDate.now());
staff[1] = new myEmployee("error!",LocalDate.now());
System.out.println(staff[0].getid());
System.out.println(staff[1].getid());
System.out.println(myEmployee.getnextid());
}
}
class myEmployee{
private static int nextid=1;
private String name;
private LocalDate hire;
private int id;
myEmployee(){
this.name = "noname";
id = nextid;
nextid++;
}
myEmployee(String name,LocalDate hire){
this.name = name;
this.hire = hire;
id = nextid;
nextid++;
}
public String getname(){
return name;
}
public LocalDate getdate(){
return hire;
}
public String toString(){
return "I am " + getname() + hire;
}
public int getid(){
return id;
}
public static int getnextid(){
return nextid;
}
public static void main(String args[]){
for(int i=0;i<10;i++){
new myEmployee();
}
if(myEmployee.getnextid() == 11)
System.out.println("true!");
else
System.out.println("false!");
}
}
package chapter4;
public class OtherClass {
private static int num=1;
public OtherClass(){
num++;
}
public static void main(String[] args) {
System.out.println("this is main");
}
public static void staticmethod(){
System.out.println("this is static method");
}
public void notstaticmethod(){
System.out.println("this not static method!");
}
public static int getnum(){
return num;
}
}
结果如下
1
this is static method
this not static method!
2
1
2
3
我么可以看到OtherClass的num确实增加了,另外从代码中也可以看出访问不同的方法采用的形式。