使用外部方法時(不管是static還是非static),都要先new一個對象,才能使用該對象的方法。
舉例如下:
測試函數(這是錯誤的):
public class Test { public static void main(String[] args) { Employee employee = null; employee.setName("旺旺"); //有警告,況且這里也執行不下去 employee.setEmail("ww@qq.com"); employee.setPwd("123333"); System.out.println(employee.getName()+" "+employee.getEmail()+" "+employee.getPwd()); } }
雖然,把Employee類中的方法都寫成static,main函數就可以調用了。但都知道,static類型在程序執行前,系統會為其分配固定的內存。如果所有方法都這樣做,系統不崩潰了。
正確的做法:
使用外部非static方法時,要先new一個對象,才能使用該對象的方法。
public class Test { public static void main(String[] args) { Employee employee = new Employee(); employee.setName("旺旺"); employee.setEmail("ww@qq.com"); employee.setPwd("123333"); System.out.println(employee.getName()+" "+employee.getEmail()+" "+employee.getPwd()); } }
public class Employee{
private Integer id; private String name; private String pwd; private String email; public Employee() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
參考: main方法為什么是靜態的