好吧,直到现在(因为我是一个初学者)我是基于程序设计编程Java,它很好,所有,但现在是时候使用Java像一个老板。在Java中的OOP - 创建对象
我正在学习OOP概念,现在写一些代码作为练习。 我不明白的是,如果我创建了几个对象是这样的:
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());
结果将是:
Age of contact [email protected] is - 25 Yosi
Age of contact [email protected] is - 22 lisa
Age of contact [email protected] is - 34 Adam
但是,如果我再尝试再次打印第一次接触,它会得到创建的最后一个对象的值。我的意思是,对于这个代码:
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());
的结果将是:
Age of contact [email protected] is - 25 Yosi
Age of contact [email protected] is - 22 lisa
Age of contact [email protected] is - 34 Adam
Age of contact [email protected] is - 34 Adam
我已经添加了对象的字符串表示,所以你可以看到不同的对象。 我以为我正在创建一个新的对象,每个对象都有它自己的实例值? 你们可以向我解释一下吗?
这是接触类:
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;
}
}
请注意,如果我删除静态预选赛我得到的错误说:“不能让一个静态的全球化志愿服务青年的非静态字段”
请发布您的联系人类的代码。最有可能的是,你有静态属性。 – alex