What is the difference between Java objects created using "new" and those that do not use "new",

What is the difference between creating an object with and without the “new”?

Example:

Thing someThing = new Thing();

against.

Path filePath = Path.get("C:\\......)

In the first example, I understand that when creating an instance of the object, this "new" allocates memory for the someThing object and that someThing refers to the memory location.

My tutorial says: “You create a Path object” using the second example. The only difference is how the object is stored or allocated memory? I am not sure why you will create an object this way.

+4
source share
7 answers

, . , API- ( ).

+12

. - factory.

, new - Path.

+6

, , : Static factory , , , , . () :

public static Path create(String name) {
    return new AbsolutePath(name); // subclass/implementation of Path
}

. , , , . . (Singleton). Etc.

: factory , :

public static Path createAbsolute(String name) { ... }
public static Path createRelative(String name) { ... }
+4

, ( , java.lang.* classe ) :

Path filePath = Path.get("C:\\......)

, , filePath, , Path. Calendar: Calendar - ,

Calendar c=Calendar.getInstance();

c GregorianCalendar.

:

class Singleton {

    private Singleton s=null;

    private Singleton(){};

    public static Singleton getSingleton() {
        if (s==null) {
            s=new Singleton();
        }
        return s;
    }
}

, getSingleton, .

+2

, .

Thing someThing = new Thing(); - Thing

Path filePath = Path.get("C:\......)

- get(), String Path -

public static Path get(String arg)
{
return path;
}
+1

Path.get . Path . . , . factory, , , , factory, .

0

In your examples, you assume that the object is created without the “new”. This is a false assumption. The object was created using the "new" in the second example.

Just because you cannot see that the “new” does not mean that it is not being called in a function.

0
source

Source: https://habr.com/ru/post/1537926/


All Articles