【问题标题】:Instantiating objects in a class from a different class with netBeans [duplicate]使用netBeans从不同的类实例化一个类中的对象[重复]
【发布时间】:2014-06-27 21:34:20
【问题描述】:

我似乎无法从已写入 main 方法的类中实例化对象。我不知道这是我的代码还是 netBeans 的问题。这是一个专门针对这个问题的 cmets 程序:

package app;
import java.util.Scanner;
public class SetUpSite {
public static void main(String[] args) {
    final int FOUNDED_YEAR = 1977;
    int currentYear;
    int age;
    statementOfPhilosophy();
    Scanner reader = new Scanner(System.in);
    //the very next line is the only line unrecognized
    EventSite oneSite = new EventSite();
    int siteNum;
    System.out.print("Enter the event site number: ");
    siteNum = reader.nextInt();
    oneSite.setSiteNumber(siteNum);
    System.out.print("Enter the Current year of the company: ");
    currentYear = reader.nextInt();
    System.out.println("The age of the Company is "+ calculateAge(FOUNDED_YEAR,        currentYear) + " years");

}

public static void statementOfPhilosophy() {
System.out.println("Event Handlers INC");
}
public static int calculateAge(final int ORIGINAL_YEAR, int currentDate) {
    int years = currentDate - ORIGINAL_YEAR;
    return years;

}

public class EventSite {
private int siteNumber;

public void oneSite() {

}
public int getSiteNumber() {
return siteNumber;
}

public void setSiteNumber(int n) {
    siteNumber = n;
}

}
}

【问题讨论】:

  • 请在您对问题的描述中投入更多精力和文字。你的问题很模糊。
  • 你怎么知道它不起作用?
  • 因为它无法编译,并且 IDE 无法识别我指定的行。上一个答案给了我所需的帮助,我只需要帮助学习如何使用我猜想的 IDE。

标签: java


【解决方案1】:

EventSite 是 SetUpSite 的一个公共内部类,这让你很困惑。从 SetUpSite 类中获取您的 EventSite 类代码,并将其放在它所属的自己的文件中。一个 Java 文件不能有多个顶级公共类。

您可以将其设为私有内部类,并将其设为静态内部类,但没有充分的理由这样做,或者可以将其设为私有并在 SetUpSite 实例之上创建它,但这是丑陋且不必要的混搭。

【讨论】:

  • 非常感谢,你真的帮了大忙。
猜你喜欢
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2011-05-29
  • 2020-01-01
  • 2018-12-15
  • 1970-01-01
相关资源
最近更新 更多