杰瑞科技汇

Java中static与new的关键区别是什么?

Of course! This is an excellent question because it touches on a fundamental concept in Java: the difference between the type of a class and an instance of that class.

Let's break it down. The phrase "static new" isn't a single Java keyword or command, but rather a combination of two keywords that are often used together in a specific context.


The Meaning of Each Keyword

static

The static keyword means that a member (a variable or a method) belongs to the class itself, not to any specific instance (object) of the class.

  • Static Variable (Class Variable): There is only one copy of this variable, shared by all instances of the class. It's created when the class is loaded into memory.
  • Static Method (Class Method): You can call this method directly on the class without needing to create an object. It cannot access instance variables or methods directly (it needs an object reference to do so).

Analogy: Think of a Blueprint (the class). A static variable is like a note written on the blueprint itself ("This house requires 20 bags of cement"). Every house built from this blueprint shares that same note. An instance variable would be the specific number of doors in one particular house (e.g., "This house has 4 doors").

new

The new keyword is the operator used to create an instance (an object) of a class.

  1. It allocates memory for the new object.
  2. It initializes the object's member variables to their default values.
  3. It calls the object's constructor, which is responsible for setting up the initial state of the object.

Analogy: new is the act of building a house from the blueprint. Each time you use new, you are constructing a new, separate house.


How They Work Together: new on a Static Context

You can't use new on the static keyword, but you often use new to create an object that is then assigned to a static variable.

This is the most common way you'll see "static" and "new" used together.

Example: A Static Factory Method

A very common and good practice is to have a static method that returns a new instance of its class. This is often called a Factory Method.

Let's look at a User class.

// File: User.java
public class User {
    // Static variable to hold a default, shared user instance
    private static User defaultUser;
    // Instance variables (belong to a specific User object)
    private String name;
    private int id;
    // Private constructor to control how User objects are created
    private User(String name, int id) {
        this.name = name;
        this.id = id;
        System.out.println("User object created for: " + name);
    }
    // Static method to get the default user
    // This method is static, so you call it on the CLASS: User.getDefaultUser()
    public static User getDefaultUser() {
        // The 'new' keyword is used HERE to create a new instance if it doesn't exist yet.
        // This is the "static new" pattern.
        if (defaultUser == null) {
            defaultUser = new User("Guest", 0); // Creating the one and only default user
        }
        return defaultUser;
    }
    public String getName() {
        return name;
    }
}

Now, let's see how we use it in another class:

// File: Main.java
public class Main {
    public static void main(String[] args) {
        // Notice we call the method on the CLASS, not an instance.
        // No 'new User()' is needed here.
        User user1 = User.getDefaultUser();
        System.out.println("User 1 name: " + user1.getName());
        // Let's get the default user again
        User user2 = User.getDefaultUser();
        System.out.println("User 2 name: " + user2.getName());
        // Are they the same object? Yes!
        System.out.println("Are user1 and user2 the same object? " + (user1 == user2));
    }
}

Output:

User object created for: Guest
User 1 name: Guest
User 2 name: Guest
Are user1 and user2 the same object? true

In this example:

  • static is used for the method getDefaultUser() and the variable defaultUser.
  • new is used inside the static method to create the actual User object.
  • The key takeaway is that new is used to create the instance, while static provides a controlled, shared way to access it.

What You CANNOT Do

You cannot use new on a static member directly.

public class MyClass {
    public static int myStaticInt = 10;
    public static void main(String[] args) {
        // This is COMPILE-TIME ERROR!
        // You cannot create a new instance of an int.
        // int newInt = new myStaticInt(); // <-- ILLEGAL
    }
}

You can only use new to create objects from classes that have a constructor. You cannot instantiate a primitive type (int, boolean, etc.) or a class that has a private constructor (unless you are inside that class, like in the factory method example).


Summary Table

Concept static new static new (The Pattern)
Purpose Belongs to the class. Creates an instance (object). A static method that returns a new instance.
Analogy The Blueprint. Building a house from the blueprint. A foreman (static method) who builds a standard model house (new) and gives you the key.
Usage MyClass.staticMethod() or MyClass.staticVar MyClass myObject = new MyClass(); MyClass myObject = MyClass.getStandardInstance();
Memory One copy shared by all. A new copy for each new. One copy (often) managed by the static method.
Example Math.PI new Scanner(System.in) User.getDefaultUser()
分享:
扫描分享到社交APP
上一篇
下一篇