简体   繁体   English

使用“new”创建的java对象和不使用“new”的java对象有什么区别

[英]what is the difference in java objects created with “new” and the ones that do not use “new”

What is the difference between creating an object with and without "new"? 使用和不使用“new”创建对象有什么区别?

example: 例:

Thing someThing = new Thing();

vs.

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

In the first example I understand that when instantiating the object, that "new" is allocating memory for a the someThing object and that the memory location is referenced by someThing. 在第一个例子中,我理解在实例化对象时,“new”是为someThing对象分配内存,而someThing引用内存位置。

My text book says " You create a Path object" by using the second example. 我的教科书使用第二个例子说“你创建一个Path对象”。 Is the difference just how the object is stored or memory is allocated? 区别在于如何存储对象或分配内存? I am not sure why you would create an object this way. 我不知道你为什么要用这种方式创建一个对象。

In the second case you are using a static method which is internally creating the object or passing a reference to an existing object. 在第二种情况下,您使用静态方法,该方法在内部创建对象或将引用传递给现有对象。 This is a common pattern particularly when the APIs wish to hide an internal implementation (as is the case here). 这是一种常见的模式,特别是当API希望隐藏内部实现时(如此处的情况)。

There is no difference. 没有区别。 The second example is a factory method. 第二个例子是工厂方法。

You pass in a few parameters and that method will call new at some point on the actual instance class of the Path . 传入一些参数,该方法将在Path的实际实例类的某个点调用new

While it behaves like a constructor, there are also differences which should be pointed out: Static factory methods do not have to return the current type, but can also return a subtype, where in contrast a constructor creates an instance of the current class. 虽然它的行为类似于构造函数,但也有一些差异需要指出:静态工厂方法不必返回当前类型,但也可以返回子类型,而构造函数则创建当前类的实例。 (Hypothetical) Example: (假设)示例:

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

From an implementation point, this gives you a lot of flexibility for later extensions. 从实现的角度来看,这为以后的扩展提供了很大的灵活性。 You can for example implement some logic, which decides which concrete type to create within the method. 例如,您可以实现一些逻辑,该逻辑决定在方法中创建哪种具体类型。 You could cache instances and return them. 您可以缓存实例并返回它们。 You could return the same instance every time (Singleton). 您可以每次返回相同的实例(Singleton)。 Etc. 等等。

Further aspect: You can actually give meaningful names to static factory methods, so code is easier to read: 更进一步:您可以为静态工厂方法提供有意义的名称,因此代码更易于阅读:

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

With the first option you are sure you are creating a new object (more or less, java.lang.* classe are a bit special) Let's take the second option: 使用第一个选项,您确定要创建一个新对象(或多或少, java.lang.* classe有点特别)让我们选择第二个选项:

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

Nothing assures you the instance you are storing in filePath is a Path one, it can be an instance of a subclass of Path. 没有什么可以保证你在filePath中存储的实例是Path one,它可以是Path的子类的实例。 Something similar occurs with Calendar: Calendar is an abstract class, so 与Calendar相似的事情:Calendar是一个抽象类,所以

Calendar c=Calendar.getInstance();

The variable c is actually a GregorianCalendar . 变量c实际上是GregorianCalendar

Another difference: 另一个区别:

class Singleton {

    private Singleton s=null;

    private Singleton(){};

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

No matter how many times you call getSingleton , you will only create one object. 无论你多少次调用getSingleton ,你只会创建一个对象。

when you are using new keyword then an object of the particular class is created. 当您使用new关键字时,将创建特定类的对象。

Here Thing someThing = new Thing(); 在这里Thing someThing = new Thing(); something is an object of Thing class 某事Thing类的一个对象

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

Path is a class having static method get() which accepts String arguments and it returns Path something like Path是一个具有静态方法get()的类,它接受String参数,并返回类似于的Path

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

The memory is allocated by the method call to Path.get in the second instance. 通过对第二个实例中的Path.get的方法调用来分配内存。 This allows the library to go through its own initialisation routines for a Path variable and which may perform additional checks. 这允许库通过自己的Path变量的初始化例程,并可以执行其他检查。 New just allocates memory. 新只是分配内存。 The memory may also be sorted and stored internally in some structure too, such that it doesn't constantly reload the same object via caching. 存储器也可以在内部以某种结构进行分类和存储,使得它不会经由高速缓存不经常地重新加载相同的对象。 I, personally, always call the factory methods rather than new up an object myself, however it could be considered to be a style thing, as pretty much everything that may be done with a factory method may also be achieved via a constructor. 我个人总是调用工厂方法而不是自己创建一个对象,但是它可以被认为是一种风格的东西,因为几乎所有可以用工厂方法完成的东西也可以通过构造函数实现。

In your examples, you are assuming that an object is created without a "new". 在您的示例中,您假设创建的对象没有“新”。 That is an incorrect assumption. 这是一个不正确的假设。 The object was created with "new" in the second example as well. 该对象也是在第二个示例中使用“new”创建的。

Just because you can't see the "new" doesn't mean it's not called in the function. 仅仅因为你看不到“新”并不意味着它没有在函数中被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java Repaint方法在旧对象之上创建新对象 - Java Repaint method creates new objects on top of old ones Java数组上的NullPointerException,已创建新对象 - NullPointerException on java array, have created new objects 'new'关键字在Java中实际上做了什么,我应该避免创建新对象吗? - What does the 'new' keyword actually do in Java, and should I avoid creating new objects? 在Java中,new TestA()和TestA obj = new TestA()有什么区别? - In Java, what is the difference between new TestA() and TestA obj = new TestA()? Java中新String()和新String(“”)的字符串初始化有什么区别? - What is the difference between String initializations by new String() and new String(“”) in Java? Java,创建新对象的意义是什么? - Java, what is the point of creating new objects? 在java中可以创建多少个嵌套的“新”对象? - How many nested “new” objects can be created in java? 为什么必须在 Eden 空间中创建新的 Java 对象? - Why must new Java objects be created in the Eden space? 在 Java 中创建的每个新 object 将对象实例变量增加一个 - Increasing an objects instance variable by one with each new object created in Java 在 JAVA 中仅使用“new”运算符时将创建多少个对象? - How many objects will be created when using only "new" operator in JAVA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM