使用外部方法时(不管是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方法为什么是静态的