从类错误Java创建新对象

时间:2014-02-11 05:40:39

标签: java class object command-line tostring

我正在尝试使用JOptionPane显示我的人物对象(姓名,年龄)。 (名称和年龄是命令行参数中的字符串和整数)。但是,我收到以下错误:

BasicClass.java:9: error: non-static variable this cannot be referenced from a static context
      Person person1 = new Person(args[0], age1);
                       ^

BasicClass.java:10: error: non-static variable this cannot be referenced from a static context
      Person person2 = new Person(args[2], age2);
                       ^

我是否正确地将第一个Person对象初始化为命令行输入?

修改的 对不起,我忘了我的代码示例:

import javax.swing.JOptionPane;

public class BasicClass{
   public static void main(String[] args){
      Integer age1 = Integer.parseInt(args[1]);
      Integer age2 = Integer.parseInt(args[3]);

   // Create two Person Objects
      Person person1 = new Person(args[0], age1);
      Person person2 = new Person(args[2], age2);

   // toString() method to display first & second Person Object
      String firstOutput = person1.toString();
      String secondOutput = person2.toString();
      JOptionPane.showMessageDialog(null, firstOutput);
      JOptionPane.showMessageDialog(null, secondOutput);
   }

   // Object
   class Person{
   // Data fields that will store each of the objects data
      private String name;
      private Integer age;

   // Constructor
      public Person(String n1, int a1){
         name = n1;
         age = a1;
      }

      public String toString(){
         String output = name + " is" + age + " years old.";
         return output;
      }
   }
}

2 个答案:

答案 0 :(得分:2)

Person是非静态内部类,这意味着它是外部类(BasicClass)实例的成员,如果没有此实例,则无法使用它(就像方法或字段)。

由于您在静态方法和静态方法中使用此类,因此没有默认的this引用

  • 制作Person课程static
  • 或创建外部类的实例,您将通过该实例创建Person类的实例,如

    BasicClass basic = new BasicClass();
    Person p = basic.new Person();
    
  • 或将Person课程的代码放在BasicClass课程之外。

答案 1 :(得分:0)

这是因为您在静态上下文中调用非静态类。一种方法是在主类中创建Person对象,然后创建主类对象。否则,您应该将Person类声明为静态类,例如

import javax.swing.JOptionPane;

public class Main{
   public static void main(String[] args){
      Integer age1 = Integer.parseInt(args[1]);
      Integer age2 = Integer.parseInt(args[3]);

   // Create two Person Objects
      Person person1 = new Person(args[0], age1);
      Person person2 = new Person(args[2], age2);

   // toString() method to display first & second Person Object
      String firstOutput = person1.toString();
      String secondOutput = person2.toString();
      JOptionPane.showMessageDialog(null, firstOutput);
      JOptionPane.showMessageDialog(null, secondOutput);
   }

   // Object
   static class Person{
   // Data fields that will store each of the objects data
      private String name;
      private Integer age;

   // Constructor
      public Person(String n1, int a1){
         name = n1;
         age = a1;
      }

      public String toString(){
         String output = name + " is" + age + " years old.";
         return output;
      }
   }
}

请参阅another example