java中的OOP - 创建对象

Yos*_*199 0 java oop object

好的家伙,到现在为止(因为我是初学者)我是基于程序编程编写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());
Run Code Online (Sandbox Code Playgroud)

结果将是:

Age of contact Contact@173f7175 is - 25 Yosi
Age of contact Contact@4631c43f is - 22 lisa
Age of contact Contact@6d4b2819 is - 34 Adam
Run Code Online (Sandbox Code Playgroud)

但是,如果我再次尝试打印第一个联系人,它将获得最后创建的对象的值.我的意思是,对于这段代码:

    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());
Run Code Online (Sandbox Code Playgroud)

结果将是:

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
Run Code Online (Sandbox Code Playgroud)

我已经添加了对象字符串表示,因此您可以看到不同的对象.我以为我正在创建一个新对象,每个对象都有自己的实例值?你们能帮我解释一下吗?

这是联系人类:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,如果我删除静态限定符,则会收到错误消息"无法对非静态字段进行静态验证"

Mar*_*nik 10

static从实例变量和/或方法(age,getAge,name,getName)中删除限定符.