Java:如何从main方法调用非静态方法? [英] Java: how to call non static method from main method?

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

问题描述

我正在学习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() { ....
 } }

所以在我的主类我宣布一个私有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.

这真的是真的重要的是你明白:

It's really important that you understand that:


  • 实例方法(和字段等)与特定实例相关

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

  • Instance methods (and fields etc) relate to a particular instance
  • Static methods and fields relate to the type itself, not a particular instance

一旦你理解了那个基础差异,有意义的是你不能在没有创建实例的情况下调用实例方法...例如,有必要问一下,那个人的高度是多少? (对于一个特定的人)但是问人的高度是多少?是没有意义的。 (没有指定一个人)。

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:如何从main方法调用非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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