在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; }}
补充知识:java中static方法与非static方法之间的调用关系
java中static方法与非static方法之间的调用关系,
有以下四种:
1、非static方法调用非static方法,直接通过方法名调用
2、static方法调用static方法,直接通过方法名调用
3、非static方法调用static方法,直接通过方法名调用
4、static方法调用非static方法,通过类对象来调用
示例如下:
package com.chendi.objectNav;public class MainClass { public static void main(String[] args){ Circle circle = new Circle(); Line line = new Line(); //静态方法调用静态方法 doSomeThing(circle); doSomeThing(line); //静态方法调用非静态方法 MainClass mainClass = new MainClass(); mainClass.noStatic(); } public void noStatic(){ //非静态方法调用非静态方法 test1(); //非静态方法调用静态方法 test2(); } public void test1(){ System.out.print('1'); } public static void test2(){ System.out.print('2'); } public static void doSomeThing(Shape shape){ shape.erase(); }}
以上这篇在java中main函数如何调用外部非static方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
1. Intellij IDEA 2019 最新乱码问题及解决必杀技(必看篇)2. java实现图形化界面计算器3. Android 7.0 运行时权限弹窗问题的解决4. IntelliJ IDEA设置条件断点的方法步骤5. 《javascript设计模式》学习笔记三:Javascript面向对象程序设计单例模式原理与实现方法分析6. ASP.NET MVC获取多级类别组合下的产品7. 关于HTML5的img标签8. ASP.NET MVC解决上传图片脏数据的方法9. ASP基础入门第七篇(ASP内建对象Response)10. 原生js XMLhttprequest请求onreadystatechange执行两次的解决
