好的,伙计们,到目前为止(因为我是初学者)我是基于过程编程的 Java 编程,这很好,但现在是时候像老板一样使用 Java。
我现在正在学习 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 Contact@173f7175 is - 25 Yosi
Age of contact Contact@4631c43f is - 22 lisa
Age of contact Contact@6d4b2819 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 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
我已经添加了对象字符串表示,因此您可以看到不同的对象。我以为我正在创建一个新对象,每个对象都有自己的实例值?你们能给我解释一下吗?
这是联系人类:
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;
}
}
请注意,如果我删除静态限定符,我会收到错误消息“无法对非静态字段进行静态引用”