簡體   English   中英

創建一個類的實例並設置變量

[英]Create instance of a class and set variables

在C#中,您可以創建一個類的實例並同時設置變量的值:

public class Object
{
    public virtual long Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Version { get; set; }
    public long ParentId { get; set; }
}

public class Start
{ 
     Object object= new Object()
     {
         Id = 1,
         Name = name,
         ParentId = parentId,
         Description = null,
         Version= 2
     };
}

Java中也可能嗎?如何?

創建實例時設置值的標准方法是僅具有一個構造函數:

class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;

    public ExampleObject(final long id, final String name, final String description, final int version, final long parentId) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.version = version;
        this.parentId = parentId;
    }
}

然后像這樣調用它:

ExampleObject exampleObject = new ExampleObject(1, name, null, 2, parentId);

可以使用與您所顯示的語法類似的語法,但是它有很多缺點,您在使用它之前應該進行研究(並且您也不能在其中使用變量):

ExampleObject exampleObject = new ExampleObject() {{
    id = 1;
    name = "";
    parentId = 2;
    description = null;
    version = 2;
}};


class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;
}

這是用靜態初始化程序塊創建一個匿名類。 靜態初始化程序塊如下所示:

class ExampleObject {
    long id;
    String name;
    String description;
    int version;
    long parentId;

    {
        id = 1;
        name = "";
        parentId = 2;
        description = null;
        version = 2;
    }
}

您可以創建一個接受所有字段值的構造函數。 這樣,您可以創建該對象的新實例並同時設置所需的值:

public class MyClass {
  public long id;
  public String name;
  public String description;
  public int version;
  public long parentId;

  /** Constructor **/
  public MyClass(long id, String name, String description, int version, long parentId) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.version = version;
    this.parentId = parentId;
  }
}

public static void main(String args[]) {
  MyClass myClass = new MyClass(1, "name", "description", 1, 1);
}

順便說一下,不建議(盡管可以)在Java中命名一個類Object ,因為Java也有一個具有相同名稱的類,並且所有 Java類都從其擴展(可能引起混淆)。

              public class Object
              {
                public long id;
                 public String name;
               public String description;
                public int version;
              public long parentId;

                  public Object(long Id,string Name,string Description,int                Version,long Parent_Id)
                {

                 this.Id =Id ;
                 this.Name =Name ;
                  this.Description =Description ;
                 this.Version =Version ;
                 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM