Results 1 to 10 of 10
  1. #1
    Chris_C's Avatar
    Chris_C is offline Member
    Join Date
    Feb 2011
    Location
    Mount Pleasant, MI
    Posts
    5
    Rep Power
    0

    Default An Array of Objects (Class Initialization)

    Hello, I'm new to the Java Forum :)

    I've recently encountered a flaw in my programming skills... either I don't understand the concept of how to fill an array with objects, or I'm implementing the methods wrong. Anyway, I keep getting a "Null Pointer Exception" when I try to run a test class (which attempts to create a few "Person" objects and put them into an array of people). If anyone could help find the reason I'm getting this exception, I would greatly appreciate it! Smarty-pants Eclipse tells me that the exception occurs at line 23 of the Database class; my assumption is that I haven't correctly given the method to create a Person object with the data that is given for the method addPerson.

    *Side-note: addPerson does a validity check on the person's gender (sex in my program's case). If it is not 'F' or 'M' it will return false, and will also return false if the array is full. This validity check also technically checks to see whether the person is actually added to the array or not (and should add the person to the people array if the returned Boolean is true.
    *Side-note2: The Weight class isn't really important here. Everything is designed correctly with that class and so it only influences one field weight which I know is not the true cause of the Null Pointer Exception.
    *Side-note3: The copyPerson method is meant to copy the skeleton of the people array and to fill it with Person objects to perform changes such as anonymizing data or performing queries to return specific values.
    *Side-note4: Lots of notes... Most of the code here is all Setters and Getters for the various fields in the classes.

    Here are the four classes:

    Person Class:
    Java Code:
    public class Person {
    	
    	private static String name;
    	private static int year;
    	private static double weight;
    	private static char sex;
    	
    	public Person(String n, int y, double w, char s) {
    		name = n;
    		year = y;
    		weight = w;
    		sex = s;
    	}
    	
    	public static void copyPerson() {
    		Database.getPeople();
    		Person[] otherPeople = new Person[Database.getPeople().length];
    		for (int i = 0; i < otherPeople.length; i++){
    			otherPeople[i] = Database.getPeople()[i];
    			i++;
    		}
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getYear() {
    		return year;
    	}
    	public void setYear(int year) {
    		this.year = year;
    	}
    	public double getWeight() {
    		return weight;
    	}
    	public void setWeight(double weight) {
    		this.weight = weight;
    	}
    	public char getSex() {
    		return sex;
    	}
    	public void setSex(char sex) {
    		this.sex = sex;
    	}
    	public static void report(boolean inMetric, Person[] people) {
    		if (inMetric = true) {
    			for (int i = 0; i < people.length; i++)
    			System.out.println(people[i]);
    		}
    		else {
    			copyPerson();
    			Weight.getStandard();
    			for (int i = 0; i < people.length; i++)
    				System.out.println(people[i]);
    		}
    	}
    }
    Database Class:
    Java Code:
    public class Database {
    	private static Person[] people;
    	private static int arrSize = 0;
    	
    	public void main (String[] args) {
    		people = new Person[100];
    	}
    	public static Person[] getPeople() {
    		return people;
    	}
    	public void setPeople(Person[] people) {
    		this.people = people;
    	}
    	public static int getArrSize() {
    		return arrSize;
    	}
    	public void setArrSize(int arrSize) {
    		Database.arrSize = arrSize;
    	}
    	public boolean addPerson(String name, int year, double weight, char sex) {
    		int counter = 0;
    		people[counter] = new Person(name, year, weight, sex);
    			counter++;
    		
    		if (sex != 'M' || sex != 'F')
    			return false;
    		else if (arrSize >= 100)
    			return false;
    		else
    			return true;
    		
    	}
    	public String report(boolean inMetric) {
    		System.out.println("Report:\n");
    		Person.report(inMetric, people);
    		return arrSize + "people.\n";
    		
    	}
    
    }
    Weight Class (not necessarily relevant to the problem, but included for reference just in case):
    Java Code:
    public class Weight {
    	private static double weight;
    
    	public static double getMetric() {
    		return weight;
    	}
    	public static double getStandard() {
    		weight = weight * 2.204623;
    		return weight;
    	}
    	public void setMetric(double weight) {
    		this.weight = weight;
    }
    	public void setStandard(double weight) {
    		this.weight = weight;
    }
    }
    Lastly, a simple Test Class:
    Java Code:
    public class TestProject {
    		public static void main(String[] args) {
    		Database db = new Database();
    		db.addPerson("Donn Sandmann", 1978, 50, 'M');
    		System.out.println(db.addPerson("Donn Sandmann", 1978, 50, 'M'));
    		db.addPerson("Hildegard Weatherby", 1988, 36, 'F');
    		db.addPerson("Shelli Steine", 1970, 45, 'F');
    		db.addPerson("Latrina Bubb", 1986, 47, 'F');
    		db.addPerson("Austin Mullan", 1990, 25, 'M');
    		db.addPerson("Bryant Wiren", 1995, 22, 'M');
    		}
    }
    Thanks in advance for help regarding the problem! I know that this task should be easy, but I suppose I don't fully understand the concepts surrounding it so I can't figure out how to hard-code it. Once someone provides me some example of how to actually add objects (e.g. Person objects) to an array of objects (e.g. Person[] people), I can figure this out :)

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    It would seem that you are initialising the People array in the main method of the Database class. Since this method never gets called (I assume you are using the main method in the TestProject class instead) the people variable is null.

  3. #3
    Chris_C's Avatar
    Chris_C is offline Member
    Join Date
    Feb 2011
    Location
    Mount Pleasant, MI
    Posts
    5
    Rep Power
    0

    Default Not Solved Just Yet!

    Wow, thanks for the catch haha. It definitely solved my problem of not being able to add elements to the array. Although I can add elements (Person objects) to the array, it seems to me that they aren't really registering correctly, or my attempted printing of the elements is not coded properly. As a matter of fact, I'm almost positive that I haven't coded my Report methods (in Person class and Database class) correctly because the program does indeed notice how many people are in the array (it prints out 6 people like it should based on the test). However, it only prints the value "null" after report. Here is my updated code:

    Person Class:
    Java Code:
    public class Person {
    	
    	private static String name;
    	private static int year;
    	private static double weight;
    	private static char sex;
    	
    	public Person(String n, int y, double w, char s) {
    		name = n;
    		year = y;
    		weight = w;
    		sex = s;
    	}
    	
    	public static void copyPerson() {
    		Database.getPeople();
    		Person[] otherPeople = new Person[Database.getPeople().length];
    		for (int i = 0; i < otherPeople.length; i++){
    			otherPeople[i] = Database.getPeople()[i];
    			i++;
    		}
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		Person.name = name;
    	}
    	public int getYear() {
    		return year;
    	}
    	public void setYear(int year) {
    		Person.year = year;
    	}
    	public double getWeight() {
    		return weight;
    	}
    	public void setWeight(double weight) {
    		Person.weight = weight;
    	}
    	public char getSex() {
    		return sex;
    	}
    	public void setSex(char sex) {
    		Person.sex = sex;
    	}
    	public static void report(boolean inMetric) {
    		if (inMetric = true) {
    			if (Database.getPeople() != null)
    			System.out.println(Database.getPeople()[Database.getArrSize()]);
    		}
    		else {
    			copyPerson();
    			Weight.getStandard();
    			for (int i = 0; i < Database.getPeople().length; i++)
    				System.out.println(Database.getPeople()[i]);
    		}
    	}
    }
    Database Class:
    Java Code:
    public class Database {
    	private static Person[] people = new Person[100];
    	private static int arrSize = 0;
    	
    	public static Person[] getPeople() {
    		return people;
    	}
    	public void setPeople(Person[] people) {
    		Database.people = people;
    	}
    	public static int getArrSize() {
    		return arrSize;
    	}
    	public void setArrSize(int arrSize) {
    		Database.arrSize = arrSize;
    	}
    	public boolean addPerson(String name, int year, double weight, char sex) {
    		people[arrSize] = new Person(name, year, weight, sex);
    		arrSize++;
    		
    		if (sex != 'M' || sex != 'F')
    			return false;
    		else if (arrSize >= 100)
    			return false;
    		else
    			return true;
    	}
    		
    	public String report(boolean inMetric) {
    		System.out.println("Report:\n");
    		Person.report(inMetric);
    		return arrSize + " people.\n";
    		
    	}
    
    }
    Weight Class (still, it doesn't really matter at this point, but just in case...):
    Java Code:
    public class Weight {
    	private static double weight;
    
    	public static double getMetric() {
    		return weight;
    	}
    	public static double getStandard() {
    		weight = weight * 2.204623;
    		return weight;
    	}
    	public void setMetric(double weight) {
    		Weight.weight = weight;
    }
    	public void setStandard(double weight) {
    		Weight.weight = weight;
    }
    }
    TestProject Class (revised, removed method instantiating the printing of the Boolean value):
    Java Code:
    public class TestProject {
    		public static void main(String[] args) {
    		Database db = new Database();
    		db.addPerson("Donn Sandmann", 1978, 50, 'M');
    		db.addPerson("Hildegard Weatherby", 1988, 36, 'F');
    		db.addPerson("Shelli Steine", 1970, 45, 'F');
    		db.addPerson("Latrina Bubb", 1986, 47, 'F');
    		db.addPerson("Austin Mullan", 1990, 25, 'M');
    		db.addPerson("Bryant Wiren", 1995, 22, 'M');
    		System.out.println(db.report(true));
    		}
    }
    I now understand the concept of correctly adding people to the array, but now it seems I've got myself screwed up on printing the elements or the elements of the Person objects are not being correctly added to the array. Because the array is not completely filled, a for loop would be useless as it would obviously print a bunch of null values (assuming that I printed the entire array), so I decided to attempt a while loop instead. It doesn't seem to function properly though. I figured that if I did a null check and printed only items whose values were not null in the array, that it would print only the indexes that were filled by a Person object. Unfortunately I know that my ideas aren't accomplishing the task :(

    Current Output:
    Java Code:
    Report:
    
    null
    6 people.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Java Code:
    if (inMetric = true)
    This is an assignment and not a comparison. You dio not need comparison when using booleans anyway.
    Java Code:
    if(bool)
    
    if( ! bool)
    I will assume the syntax of this line is correct
    Java Code:
    System.out.println(Database.getPeople()[Database.getArrSize()]);
    Think about what value getArrSize will return. Initially it is 0. If you add a Person it gets added at index 0 and then arrSize gets incremented to 1. Then if you attempt to print the Person at this index it will be null because the only Person you added was at index 0. All other indicies are null.

    Aside from that I don't think this is the best way to go about it. Do you think that if you want to print out a bunch of information that you would ask a single Person to output the info about all the other Person's in the world? I wouldn't do it that way. So who/what is responsible for knowing about all the Person's? Database of course. In the Darabase report method I would have a loop that iterates over the Person array and displays each Person object.

  5. #5
    Chris_C's Avatar
    Chris_C is offline Member
    Join Date
    Feb 2011
    Location
    Mount Pleasant, MI
    Posts
    5
    Rep Power
    0

    Default

    Apparently I'm not the best Java-code proof-reader... the fact that you don't need to run a comparison on Boolean values actually completely changed the report! And I'm not the best instruction-reader either... although to be frank our instructor doesn't write instructions very well. He specified that he wanted Database.report() to return a string with a format kind of like this: "Report: \n PERSONS CONTAINED IN THE DATABASE \n Number of people", but at the same time he wanted the Person.report() method to return a string as well, but subtly said that it should reverse the order of the fields "weight" and "sex" when generating the report. I suppose I got confused because they both returned strings and Person.report() had to be called by Database.report(). The entire syntax of his instructions is a little cooky...

    But anyway, I've not gotten much farther since the last time you gave me some things to think about... I THINK that the people added to my Person[] array have all their attributes (fields) in order; I can successfully add them, I know that much from what it printed out. However, what is printed out are not the attributes of the people, but rather what seems to be the memory address... I don't know if there is a specific technique for printing objects and their properties, but so far I have not been able to read up on such methods. My current program definitely understands that people have been added to the array, as it correctly increments arrSize and prints an accurate number of people in the report. However, as I said, the people that ARE printed are nothing but gibberish instead of their assigned attributes, and it STILL prints out the rest of the 94 null-index locations in the array even though I use a while loop specifically stating that 'if the next index is null, don't print it and then exit the loop'. I took into account your previous hint that if I try to print the person I just indexed, it will result in a null. I corrected this by changing that specific parameter to arrSize-1. Here are the updated Database and Person classes (with a few extra programming assignment requirements thrown in that I started coding but won't work until I get the report methods correct):

    Person:
    Java Code:
    public class Person {
    	
    	private static String name;
    	private static int year;
    	private static double weight;
    	private static char sex;
    	
    	public Person(String n, int y, double w, char s) {
    		name = n;
    		year = y;
    		weight = w;
    		sex = s;
    	}
    	
    	public static void copyPerson() {
    		Database.getPeople();
    		Person[] otherPeople = new Person[Database.getPeople().length];
    		for (int i = 0; i < otherPeople.length; i++){
    			otherPeople[i] = Database.getPeople()[i];
    			i++;
    		}
    	}
    	public String getName() {
    	public static void setName(String name) {
    	public int getYear() {
    	public static void setYear(int year) {
    	public double getWeight() {
    	public static void setWeight(double weight) {
    	public char getSex() {
    	public static void setSex(char sex) {
    	public static int yearToAge(int year) {
    	public static void report(boolean inMetric) {
    		
    		}
    	}
    Database:
    Java Code:
    public class Database {
    	private static Person[] people = new Person[100];
    	private static int arrSize = 0;
    	
    	public static Person[] getPeople() {
    		return people;
    	}
    	public void setPeople(Person[] people) {
    		Database.people = people;
    	}
    	public static int getArrSize() {
    		return arrSize;
    	}
    	public void setArrSize(int arrSize) {
    		Database.arrSize = arrSize;
    	}
    	public boolean addPerson(String name, int year, double weight, char sex) {
    		people[arrSize] = new Person(name, year, weight, sex);
    		arrSize++;
    		
    		if (sex != 'M' || sex != 'F')
    			return false;
    		else if (arrSize >= 100)
    			return false;
    		else
    			return true;
    	}
    		
    	public void anonomizeName() {
    		Person.copyPerson();
    		Person.setName("Anon");
    		report(true);
    	}
    	public void anonomizeAge() {
    		Person.copyPerson();
    		Person.setYear(2011);
    		report(true);
    	}
    	public void anonomizeWeight() {
    		Person.copyPerson();
    		Person.setWeight(0);
    		report(true);
    }
    	public void anonomizeSex() {
    		Person.copyPerson();
    		Person.setSex('?');
    		report(true);
    }
    	public String report(boolean inMetric) {
    		if (inMetric) {
    			while (people[arrSize-1] != null)
    			System.out.println(people[arrSize-1]);
    		}
    		else {
    			Person.copyPerson();
    			Weight.getStd();
    			for (int i = 0; i < people.length; i++)
    				System.out.println(people[i]);
    		}
    		return arrSize + " people.";
    		
    	}
    }
    My exact output when I run the TestProgram class:
    Java Code:
    Person@7919298d
    Person@62f72617
    Person@4fe5e2c3
    Person@7d8a992f
    Person@164f1d0d
    Person@23fc4bec
    null \n --> [B][U]this is repeated 93 more times...[/U][/B]
    6 people.
    I can't figure out how to make it only print the indexed elements (and not the null elements). I thought that by using a while loop with the bounds |people[arrSize-1] != null| would do it, but it seems to be ignoring this requirement and printing everything anyway, regardless of the index's value. Also, in the Person.report() method I am supposed to change the order of the weight and sex of the person object. I really have no clue how to even get started on that. My main problem is that I don't really know how to print objects (and their fields). I swear I never learned any of this in class, not even in last semester's course...

    Once again, thank you for all your help. You've definitely helped me understand some concepts that I apparently need to practice that I never learned! :)

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Person@7919298d

    You get that output because your Person class does not override the toString method and it inherits it from Object.

    Currently you are printing out every element in the array even if they are empty/null. But you only want to print out the elements where you have stored a Person object. So don't print upto the length of the array. Only print upto how many objects in the array. What are you using to store how many objects you have in the array?

  7. #7
    Chris_C's Avatar
    Chris_C is offline Member
    Join Date
    Feb 2011
    Location
    Mount Pleasant, MI
    Posts
    5
    Rep Power
    0

    Default

    Ha, thanks for the tip but through a massive google excursion I did indeed find information on the toString method :) I did figure out how to override that, and it prints single people out perfectly now. And the null-printing problem is gone. I was using a while loop which apparently doesn't work in this situation. I had a for loop at one point, but removed it because I thought that it was the cause of the problem that toString actually happened to be the cause of. Anyway, now it's printing the correct number of people, but not printing out the right people... Here is the output below:

    Report:
    Bryant Wiren, 15, M, 22.0 kg
    Bryant Wiren, 15, M, 22.0 kg
    Bryant Wiren, 15, M, 22.0 kg
    Bryant Wiren, 15, M, 22.0 kg
    Bryant Wiren, 15, M, 22.0 kg
    Bryant Wiren, 15, M, 22.0 kg
    6 people.
    It's only printing the last person, and I know that the cause of the problem is in one of the report() methods, either in Database.report() or Person.report(). I'm going to take a wild guess and say it's in Database.report() because I'm not correctly incrementing the array of objects, so it just prints the last data that was entered for "name", "year", "weight" and "sex", which is the last person added (Bryant Wiren). So now my question is, how exactly do I traverse the Person[] people array with my current report methods? I'm calling Person.report() correctly to ignore the toString automatic method, which prints the person correctly, but I'm not printing out each element of the array, only the last. Here are the two classes (the TestProject class is still the same, and the Weight class doesn't matter at the moment):

    Person Class:
    Java Code:
    public class Person {
    	
    	private static String name;
    	private static int year;
    	private static double weight;
    	private static char sex;
    	
    	public Person(String n, int y, double w, char s) {
    		name = n;
    		year = y;
    		weight = w;
    		sex = s;
    	}
    	
    	public static void copyPerson() {
    		Database.getPeople();
    		Person[] otherPeople = new Person[Database.getPeople().length];
    		for (int i = 0; i < otherPeople.length; i++){
    			otherPeople[i] = Database.getPeople()[i];
    			i++;
    		}
    	}
    	public static String getName() {
    		return name;
    	}
    	public static void setName(String name) {
    		Person.name = name;
    	}
    	public static int getYear() {
    		return year;
    	}
    	public static void setYear(int year) {
    		Person.year = year;
    	}
    	public static double getWeight() {
    		return weight;
    	}
    	public static void setWeight(double weight) {
    		Person.weight = weight;
    	}
    	public static char getSex() {
    		return sex;
    	}
    	public static void setSex(char sex) {
    		Person.sex = sex;
    	}
    	public static int yearToAge(int year) {
    		return 2010 - year;
    	}
    	public static String report(boolean inMetric) {
                    System.out.println("Report:");
    		if (inMetric)
    			return (getName() + ", " + yearToAge(year) + ", " + getSex() + ", " + getWeight() + " kg");
    		else
    			return (name + ", " + yearToAge(year) + ", " + sex + ", " + Weight.getStd() + " lbs");
    		
    		
    		}
    	}
    Database Class:
    Java Code:
    public class Database {
    	private static Person[] people = new Person[100];
    	private static int arrSize = 0;
    	
    	public static Person[] getPeople() {
    		return people;
    	}
    	public void setPeople(Person[] people) {
    		Database.people = people;
    	}
    	public static int getArrSize() {
    		return arrSize;
    	}
    	public void setArrSize(int arrSize) {
    		Database.arrSize = arrSize;
    	}
    	public boolean addPerson(String name, int year, double weight, char sex) {
    		people[arrSize] = new Person(name, year, weight, sex);
    		Person.setName(name);
    		Person.setYear(year);
    		Person.setSex(sex);
    		Person.setWeight(weight);
    		arrSize++;
    		
    		if (sex != 'M' || sex != 'F')
    			return false;
    		else if (arrSize >= 100)
    			return false;
    		else
    			return true;
    	}
    		
    	public void anonomizeName() {
    		Person.copyPerson();
    		Person.setName("Anon");
    		report(true);
    	}
    	public void anonomizeAge() {
    		Person.copyPerson();
    		Person.setYear(2011);
    		report(true);
    	}
    	public void anonomizeWeight() {
    		Person.copyPerson();
    		Person.setWeight(0);
    		report(true);
    }
    	public void anonomizeSex() {
    		Person.copyPerson();
    		Person.setSex('?');
    		report(true);
    }
    	public String report(boolean inMetric) {
    		if (inMetric) {
    			for (int i = 0; i < arrSize; i++) {
    				System.out.println(Person.report(inMetric));
    			}
    		}
    		else {
    			Person.copyPerson();
    			Weight.getStd();
    			for (int i = 0; i < people.length; i++)
    				System.out.println(people[i]);
    		}
    		return arrSize + " people.";
    		
    	}
    }
    Again, thanks for the help :) I've come a long way since I started haha. But a side-note; when changing from metric to standard (via the Weight class), the number that comes out isn't always pretty (multiply kg by about 2.20572345 or something similar to get lbs). Simply put, I can't use printf (that I can see) when returning the String in the Person.report() method, so how would I round the conversion of kg to lbs (in the weight class, listed in my first post)? Is there some utility that does this? Java.util.math perhaps? I don't know any other way to round other than with printf when giving output. I know there is at least one other way, but I don't know it. If you provide that method, could you give me an example? :)
    Last edited by Chris_C; 02-09-2011 at 03:43 AM.

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Your problem is that you have made all the member variables of the Person class static. This means they belong to the class and not an instance of the class. Whenever you call a setXXX method you change a variable that all Person objects see.
    Java Code:
    people[arrSize] = new Person(name, year, weight, sex);
    Person.setName(name);
    Person.setYear(year);
    Person.setSex(sex);
    Person.setWeight(weight);
    Also, the first line creates a new Person object. Why do you then call all those setXXX methods?

  9. #9
    Chris_C's Avatar
    Chris_C is offline Member
    Join Date
    Feb 2011
    Location
    Mount Pleasant, MI
    Posts
    5
    Rep Power
    0

    Default Static vs Non-Static

    Well, to first clarify why I called the four methods "Person.setXXXXXX()": I was thinking that for some reason I may not have correctly assigned attributes to the Person objects when I instantiated them, so I threw those four method calls to potentially fix that problem if it did indeed occur. Turns out though that after getting rid of those four method calls I'm still printing out the same person object over and over.

    One of my biggest problems in coding is that I don't understand the concept of static vs non-static modifiers. I thought that setters and getters would allow data access between the classes, and that's what they did. Unfortunately though Eclipse was telling me that "x element could not be referenced in a static context" or vice-versa, depending on the specific element. So I basically made everything static to get it to stop warning me about static issues. Did making everything static screw things up? I just removed the Static modifier for everything in the Person class and made changes accordingly (changing Person.fieldName to this.fieldName, etc.). That created a bunch of errors in the Database class though. I can't "make a static reference to the non-static method setName(String) from the type Person" and "The method setName(String) is undefined for the type Database". That's why I made everything static in the first place. To stop these errors from happening.

    Assuming the Database class stays the same and everything in the Person class has its static modifiers removed, could you explain why the two above errors are occurring? I don't understand the difference of static vs non-static to a great extent, so I don't understand why I can't simply call Person.setName("Anon") in Database.anonomizeName(). Is there something special I have to do now? I wish my professor had taught us more about this last semester... Sorry for the huge waste of time by the way. I'm sure this is a completely noob question. I just don't get it.

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    "static" on a field means that there is only one of them shared between all the instances of a class. Similarly for methods: but this introduces a restriction...

    Java Code:
    class Bad {
        int foo;
    
        static void bar() {
            foo = 666; // <-- the compiler will not accept this
        }
    }

    If the method foo() is static it can only access static members of its class. This makes sense if you think about it: there is only one foo() method shared between all the instances of Bad but each instance has its own foo. The compiler won't accept that line because it has no clue which foo is being set.

    Next think about the following:

    Java Code:
    class Bad2 {
        int foo;
        void bar() {
            foo = 666; // <-- This is OK
        }
    
        public static void main(String[] args) {
            foo = 666; // <-- This is not
            bar();  // <-- neither is this
        }
    }

    The bar() method is OK now. There is one foo() per instance so the line "foo=666;" makes perfect sense. It means "set the foo of the instance this foo() method belongs to, to 666".

    But the two lines in main() will lead to the message about "static context" for the same reason that Bad was bad: main() is static (one method shared between every instance of Bad2) but there is nothing to say which foo should be set or which bar() should be called. (There's one each of them for each instance.

    -------------------

    My rule of thumb about static is "don't use it". With the solitary exception of static void main(), just say no to static.

    And don't feed static to your compiler to keep it happy. Would you feed morphine to your child for that purpose? Instead remove all of the static modifiers (the single exception noted) then fix the code by following the helpful messages that the compiler gives. (Getting help here if need be, or from the observations I made above, to understand each and every one of the helpful messages.)
    Last edited by pbrockway2; 02-09-2011 at 06:53 AM.

Similar Threads

  1. Class Instance initialization fails
    By JOHNINALBANY in forum New To Java
    Replies: 3
    Last Post: 07-08-2012, 08:43 PM
  2. Replies: 1
    Last Post: 01-03-2010, 10:48 PM
  3. Replies: 1
    Last Post: 11-17-2008, 10:32 AM
  4. Array initialization difference
    By sln69 in forum Advanced Java
    Replies: 2
    Last Post: 10-10-2008, 03:38 AM
  5. 2D Array Initialization
    By M77 in forum Advanced Java
    Replies: 3
    Last Post: 06-04-2008, 03:12 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •