【问题标题】:How to call non-static method in another class's static method in java?如何在java中另一个类的静态方法中调用非静态方法?
【发布时间】:2017-05-18 19:32:06
【问题描述】:

我的一个班级有这个方法

@Override
public void liveFlights(int one, int two, int three, int four, int five,
                        int six, int seven, int eight, int nine, int ten, int eleven, int twelve) {
    System.out.println("There is "+counter+" flights at this moment ");

    System.out.println("England to Netherland at 12.00 pm "+one+"is flight number");
    System.out.println("Netherland to England at 12.00 pm "+two+"is flight");
    System.out.println("Turkey to USA at 06.00 pm "+three+"is flight number");

我想在这个静态方法(另一个类)中调用这个非静态方法

public static void searchResEntry() throws java.io.IOException  // start of method
{
    // variable declarations
    String Name;
    String Address;
    Scanner read = new Scanner(System.in);
    System.out.print("Please enter your following information for your reservation result:  \n");   // displaying the information to enter for searching a reservation

    System.out.print("  Enter Name  :   "); // displaying message to enter name
    Name = read.nextLine(); // prompt for the name
} 

有什么帮助吗??

【问题讨论】:

  • 你的静态方法需要一个包含非静态方法的类的实例。

标签: java methods static non-static


【解决方案1】:

将包含非静态方法的类的实例传递给静态方法

public static void searchResEntry(YourClass instance) throws java.io.IOException    // start of method
    {
        // variable declarations
        instance.liveFlights(...);

或在其中创建实例:

public static void searchResEntry() throws java.io.IOException    // start of method
    {
        // variable declarations
        YourClass instance = new YourClass();
        instance.liveFlights(...);

【讨论】:

  • 我忘了添加,非静态方法在我的抽象类中,为什么实例认为不起作用。这取决于吗?
  • 因为你不能实例化抽象类,所以在其中实现非静态(实例)方法是没有意义的,除非你有一些extends这个抽象类的类。要么将此方法声明为abstract,并在扩展抽象类的类中提供实现,要么将此方法声明为static
猜你喜欢
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 2022-11-18
相关资源
最近更新 更多