• 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方法为什么是静态的

  • 相关阅读:
    剑指offer 数值的整数次方
    剑指offer 链表中倒数第K个节点
    剑指offer反转链表
    剑指offer 栈的压入弹出 顺序
    剑指offer 二叉搜索树后续遍历序列 判断
    剑指offer 复杂链表的复制 (有向图的复制)
    剑指offer 二叉搜索树与双向链表
    2018/03/15 常用的超全局变量
    2018/03/14 每日一个Linux命令 之 ln
    PHP使用 zip 扩展压缩文件
  • 原文地址:https://www.cnblogs.com/liushao/p/6382135.html
Copyright © 2020-2023  润新知