Java:如何从主方法调用非静态方法? [英] Java: How To Call Non Static Method From Main Method?

查看:63
本文介绍了Java:如何从主方法调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java,现在我遇到了以下问题:我将 main 方法声明为

I'm learning java and now i've the following problem: I have the main method declared as

public static void main(String[] args) {

..... }

在我的主要方法中,因为它是静态我只能调用其他静态方法!!!为什么?

Inside my main method, because it is static I can call ONLY other static method!!! Why ?

例如:我还有一堂课

 public class ReportHandler {       
     private Connection conn;   
     private PreparedStatement prep;
     public void executeBatchInsert() { ....
 } }

所以在我的主类中我声明了一个 private ReportHandler rh = new ReportHandler();

So in my main class I declare a private ReportHandler rh = new ReportHandler();

但是如果它们不是静态的,我就不能调用任何方法.

But I can't call any method if they aren't static.

这是哪里出了问题?

抱歉,我的问题是:如何设计"应用程序以允许我从起点"(static void main)调用其他类.

sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the static void main).

推荐答案

你只需要创建一个ReportHandler的实例:

You simply need to create an instance of ReportHandler:

ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions

实例方法的重点是它们专用于类的特定实例...因此您需要先创建一个实例.这样,实例将可以访问您的案例中的正确连接和准备好的语句.仅仅调用ReportHandler.executeBatchInsert,没有足够的上下文.

The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.

了解这一点非常重要:

  • 实例方法(和字段等)与特定实例相关
  • 静态方法和字段与类型本身相关,不是特定实例

一旦你理解了这个根本区别,你就可以在不创建实例的情况下调用实例方法是有道理的......例如,问那个的高度是多少是有道理的

Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).

假设您是从一本书或教程中学习 Java,您应该阅读更多静态和非静态方法的示例等 - 这是理解的重要区别,您将拥有各种问题,直到你理解为止.

Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.

这篇关于Java:如何从主方法调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆