简体   繁体   English

创建新的Java Object实例时,在匿名代码块中初始化变量是否兼容?

[英]Is that compatible that initializing variables in an anonymous code block when creating a new Java Object instance?

Just like this : 像这样 :

class Car {
    int carId;
    String brand;
    public Car(int carId, String brand) {
        this.carId = carId;
        this.brand = brand;
    }
    // getter and setter
    public String toString() {
        return " car :" + "id - " + carId + ", brand - " + brand;
    }
}
public class User {
    String name;
    Car car;
    // getter and setter
    public String toString() {
        return name + " has a " + car.toString();
    }
    public static void main(String[] args) {
        // 1st
        User u = new User() {
            { // my problem is here : is this block OK?
                setName("Tom");
                setCar(new Car(1, "Volvo"));
            }
        };
        // 2nd or this
        // Car car = new Car(1, "Volvo");
        // User u = new User();
        // u.setName("Tom");
        // u.setCar(car);

        System.out.println(u);
    }
}

I know this works fine in C#, and it seems that it also works in Java. 我知道这在C#中可以正常工作,而且似乎在Java中也可以。 However, it's really not clear that if that's right or a good code style... Really thanks for your help! 但是,实际上还不清楚是正确的还是良好的代码样式...真的,谢谢您的帮助!

In Java, you are creating an anonymous inner class here. 在Java中,您正在此处创建一个匿名内部类

So that object is not a User , but a subclass of User . 这样的对象不是User ,而是一个子类User

It is pretty uncommon, and most people consider it bad style. 这种情况很少见,大多数人认为它是不好的风格。 Some people use it "by accident" (not knowing what they are doing), a few suggest to follow this pattern. 有些人“偶然”使用它(不知道自己在做什么),有些人则建议遵循这种模式。 But in general, it will surprise most of your readers, and a base rule in programming is to avoid doing that. 但是总的来说,这会让大多数读者感到惊讶,而编程的基本规则就是避免这样做。 You follow conventions, even when they are informal and not written down. 您遵守约定,即使这些约定是非正式的且未写下来。

And for the record: depending on how you implemented your own equals() method, this approach of creating sub class instances on the fly might even lead to bizarre bugs. 记录在案:根据您如何实现自己的equals()方法,这种动态创建子类实例的方法甚至可能导致奇怪的错误。

Therefore: simply don't do it. 因此:根本不要这样做。

In c# there is a construct called Object Initializer and it looks syntactically similar to what you tried to do here. c#有一个称为Object Initializer的构造,其语法在语法上类似于您在此处尝试执行的操作。

However, this does not exist in Java . 但是,这在Java中不存在。

What you proposed is a combination of an Anonymous Class Declaration and an Instance Initializer that is sometimes refererred to as "Double Brace Initialization" and comes with several serious caveats - see this question for even more reasons to avoid this in addition to the valid points GhostCat mentioned in his answer . 您建议的是匿名类声明实例初始化程序的组合,该实例初始化程序有时被称为“双括号初始化”,并带有一些严重的警告-除了GhostCat的有效点之外,请参阅此问题以了解更多避免这种情况的原因。 在他的回答中提到

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM