OK guys, up till now (and since I'm a beginner) I was programming Java based on procedural programming and it was nice and all but It's time to use Java like-a-boss.
I'm learning the OOP concept now while writing some code as practice. What I dont understand is that if I create a few objects this way:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
The result will be:
Age of contact Contact@173f7175 is - 25 Yosi
Age of contact Contact@4631c43f is - 22 lisa
Age of contact Contact@6d4b2819 is - 34 Adam
But if I then try to print the first contact again, it will get the values of the last object created. I mean, for this code:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
the result will be:
Age of contact Contact@173f7175 is - 25 Yosi
Age of contact Contact@4631c43f is - 22 lisa
Age of contact Contact@6d4b2819 is - 34 Adam
Age of contact Contact@173f7175 is - 34 Adam
I've added up the object string representation so you can see the different objects. I thought I was creating a new object and each object has it's own instance values? could you guys explain to me?
This is the contacts class:
public class Contact {
private static int age = 0;
private static String name = "Unknown";
private static String gender = "Male";
public Contact(int a, String n, String g) {
age = a;
name = n;
gender = g;
}
public Contact() {
}
public static int getAge() {
return age;
}
public static String getName() {
return name;
}
public static String getGender() {
return gender;
}
public static void setAge(int a) {
age = a;
}
public static void setName(String n) {
name = n;
}
public static void setGender(String g) {
gender = g;
}
}
Please note that if I remove static qualifier I get errors saying "cannot make a static referance to the non static field"