0

How do I get each addresses from each of the objects from my code. The code seems right. But it return only the House2 address, both times. It didn't return the first address.

    public class House {

    private static String address;

    House ( String addr ) {

        address = addr;

    }

    public static String returnAddress () {
        return address;
    }

    public static void main (String [] args) {

        House house1 = new House("house 1 address");
        House house2 = new House("house 2 address");


        System.out.println( house1.returnAddress());
        System.out.println( house2.returnAddress());

    }
}
QuartZ
  • 154
  • 3
  • 12
  • The address field should not be static since by making it static, each house will share the very same address (as you're finding out). If you make it an instance (non-static) field, then each house instance will have its own address, and your program will have a better chance of working correctly. – Hovercraft Full Of Eels May 04 '15 at 03:42
  • That's because your `returnAddress()` method shouldn't be static either. Read the tutorial on [Java Object-Oriented Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html) - it's all explained well there. – Hovercraft Full Of Eels May 04 '15 at 03:45
  • Yup. You got it. Thank you. I'm sorry for wasting your time. The solution is simpler than i thought. I already google it before, but didn't find the ones that seem the same as mine. Thanks. You're awesome. – QuartZ May 04 '15 at 03:49
  • Also, `getAddress()` is more conventional for Java, rather than `returnAddress()`. – Tyler Petrochko May 04 '15 at 03:52

1 Answers1

1

Remove the static keyword. A static variable is global, meaning it's shared across all instances of that class, as opposed to a non-static variable, which is specific to each instance itself. When you make the first house, you're setting address to the the first string ("house 1 address"), which is SHARED by all houses, and when you instantiate the second, you're setting address to the second string ("house 2 address"). Accordingly, remove the static keyword from returnAddress().

Tyler Petrochko
  • 2,611
  • 4
  • 24
  • 30