zoukankan      html  css  js  c++  java
  • java中main函数怎么调用外部非static方法

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

  • 相关阅读:
    WEB浏览器与服务器通讯过程
    lua及luci学习
    让apache2不开机启动,管理Ubuntu的开机启动项
    在linux中如何调试C语言程序
    如何去除configure的默认选择-g O2
    C语言使用SQLite3数据库
    Linux下的C程序如何调用系统命令,并获取系统的输出信息到C程序中
    Opencv step by step
    Opencv step by step
    Opencv step by step
  • 原文地址:https://www.cnblogs.com/liushao/p/6382135.html
Copyright © 2011-2022 走看看