2 Replies - 307 Views - Last Post: 07 October 2012 - 04:34 PM Rate Topic: -----

#1 holidaze  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 27-September 12

Error: non-static variable can't be referenced (Object creation)

Posted 07 October 2012 - 01:46 PM

Hello,

I am getting the following error for lines 10 and 11(object creation).
SimpleClass.java:16: error: non-static variable this cannot be referenced from a static context

If I delete the static in 'public static void main(String[ ] args) {' then the error goes away, but I get a error stating 'No main methods, applets, or MIDIets found in file'.

Anyone have any ideas?
Thanks,

import javax.swing.JOptionPane;

   public class SimpleClass {
      public static void main(String[ ] args) {
		
	    int age1 = Integer.parseInt(args[1]);
	    int age2 = Integer.parseInt(args[3]);
			
       	    //creates two persons objects
            Person person1 = new Person(args[0], age1);
            Person person2 = new Person(args[2], age2);
      	
	    //Prints the first JPane with relative data fields
	    String display1 = person1.toString();
	    JOptionPane.showMessageDialog(null, display1);

	    //Prints the second JPane with relative data fields
	    String display2 = person2.toString();
	    JOptionPane.showMessageDialog(null, display2);
   	}//end of class

/*Stores the name and age of the person*/
   class Person{
    //data fields that store each object's data
      private String name;
      private int age;
   	
   /** Constructor - Used To Create EAch Object & Initialize DAta Fields.
   * @param n1 is the Persons name 
   * @param a1 is the Persons age*/  
      public Person(String n1, int a1){
         name = n1;
         age = a1; 
      }
   	
   //Used to Display The Data Stored In EAch Object's DAta Field.
	public String toString(){
		String personString = name + " is " + age + " years old.";
		return personString;
   }
  }
 }


Is This A Good Question/Topic? 0
  • +

Replies To: Error: non-static variable can't be referenced (Object creation)

#2 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • Posts: 2,620
  • Joined: 29-July 11

Re: Error: non-static variable can't be referenced (Object creation)

Posted 07 October 2012 - 03:57 PM

You person class. Make it

static class Person {

}




You have a class, SimpleClass, with an inner class Person. The JVM is complaining because no instance of SimpleClass exists, thus no instance of Person can exist at that point in time.
Was This Post Helpful? 0
  • +
  • -

#3 holidaze  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 27-September 12

Re: Error: non-static variable can't be referenced (Object creation)

Posted 07 October 2012 - 04:34 PM

Problem Solved. I chose to place the Person class outside my main public class. Thanks for the help!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1