简体   繁体   English

通过Java中的三种不同方式,初始化对象有什么用?

[英]What is the use of initialize object through three different ways in Java?

I am working with Java as beginner i was following a tutorial ( http://www.javatpoint.com/object-and-class-in-java ) which states that there are three different way through which one can initialize an object into java. 我是一名初学者,因此我正在使用Java,我正在学习一个教程( http://www.javatpoint.com/object-and-class-in-java ),该教程指出可以通过三种不同的方法将对象初始化为Java 。

  1. By reference variable 通过参考变量
  2. By method 按方法
  3. By constructor 按构造函数

My Question is that what is the significance of using three different method for a single task. 我的问题是,对单个任务使用三种不同的方法有何意义?

Example: 1) Object and Class Example: Initialization through reference 示例:1)对象和类示例:通过引用进行初始化

 class Student{  
     int id;  
     String name;  
    }  
    class TestStudent2{  
     public static void main(String args[]){  
      Student s1=new Student();  
      s1.id=101;  
      s1.name="Sonoo";  
      System.out.println(s1.id+" "+s1.name);//printing members with a white space  
     }  
    }  

2) Object and Class Example: Initialization through method 2)对象和类示例:通过方法进行初始化

    class Student{  
     int rollno;  
     String name;  
     void insertRecord(int r, String n){  
      rollno=r;  
      name=n;  
     }  
     void displayInformation(){System.out.println(rollno+" "+name);}  
    }  
    class TestStudent4{  
     public static void main(String args[]){  
      Student s1=new Student();  
      Student s2=new Student();  
      s1.insertRecord(111,"Karan");  
      s2.insertRecord(222,"Aryan");  
      s1.displayInformation();  
      s2.displayInformation();  
     }  
    } 

3) Object and Class Example: Initialization through constructor 3)对象和类示例:通过构造函数初始化

class Employee{  
        int id;  
        String name;  
        float salary;  
        void insert(int i, String n, float s) {  
            id=i;  
            name=n;  
            salary=s;  
        }  
        void display(){System.out.println(id+" "+name+" "+salary);}  
    }  
    public class TestEmployee {  
    public static void main(String[] args) {  
        Employee e1=new Employee();  
        Employee e2=new Employee();  
        Employee e3=new Employee();  
        e1.insert(101,"ajeet",45000);  
        e2.insert(102,"irfan",25000);  
        e3.insert(103,"nakul",55000);  
        e1.display();  
        e2.display();  
        e3.display();  
    }  
    } 

What is the significance of using three different method for a single task. 对单个任务使用三种不同方法的意义何在?

It's the same significance as any task in software development: there are often multiple ways of writing code that would result in the same eventual state, and so we consider which one of these is most appropriate. 它与软件开发中的任何任务都具有相同的意义:通常有多种编写代码的方法会导致最终状态相同,因此我们考虑其中最合适的一种。 Arguably (IMHO), this is the real skill of development: not simply being able to make the computer do a particular thing, but writing code to do that thing that is as simple/clean/understandable/extensible as it possibly can be. 可以说(IMHO),这是开发的真正技能:不仅能够使计算机执行特定任务,而且编写代码以尽可能简单/简洁/可理解/可扩展地完成该任务。

In this specific case, I would strongly recommend initialising the fields through the constructor. 在这种特定情况下,我强烈建议您通过构造函数初始化字段。 Sometimes it makes sense for an object's fields to be mutable, and to be initialised after the object is created (as in cases 1 and 2). 有时,使对象的字段可变并在创建对象后对其进行初始化是有意义的(如情况1和2)。 But in most cases - and especially here with "id" fields that define the object itself - it is clearest if the object is constructed with those fields. 但是在大多数情况下-特别是在这里带有定义对象本身的“ id”字段的情况下-如果用这些字段构造对象是最清楚的。 This way there's no point where the object is in an invalid state; 这样,对象就不会处于无效状态。 it's impossible to create an Employee object that has no id . 创建没有idEmployee对象是不可能的。

Note that what you've pasted for example 3 is not an example of constructor initialisation! 请注意,您粘贴的示例3 并非构造函数初始化的示例! Read the page carefully, they say they will cover this later. 请仔细阅读页面,他们说稍后会介绍。 The code you've pasted is unrelated. 您粘贴的代码无关。

I would do something like the following: 我将执行以下操作:

class Student{  
  final int id;  
  final String name;  

  // This is the constructor that will initialise the fields with what's passed in
  // (Note that because the fields are final, they MUST be set by the constructor)
  public Student(int id, String name) {
    this.id = id;
    this.name = name;
  }
}

class TestStudent6 {  
  public static void main(String args[]){  
    Student s1 = new Student(101, "Sonoo");  
    System.out.println(s1.id + " " + s1.name); //printing members with a white space  
  }  
}  

(Note that I'd probably also make the id and name fields private and set up getId() and getName() methods to access them instead, but that's outside the scope of what you asked.) (请注意,我可能还会将idname字段设为私有,并设置getId()getName()方法来访问它们,但这超出了您的要求。)

Objects have state and its internal to it, hence it should be best made hidden from the outside ie not accessible to outside classes. 对象具有state及其内部,因此最好将其隐藏在外部,即外部类无法访问。 There will be other classes which may be dependent upon the object. 可能还有其他类可能取决于对象。 Ideally these external classes should depend upon the public methods to modify or read the state. 理想情况下,这些外部类应依赖于公共方法来修改或读取状态。 Hiding the internal details (states) and exposing only the needed methods is a good idea. 隐藏内部细节(状态)并仅公开所需的方法是一个好主意。

Now we have our fields encapsulated so in brief see initilization using constructor vs setters. 现在我们已经封装了字段,因此简要介绍了使用构造函数vs setter方法的初始化。 If a class is composed of few fields without which an object of that class do not make sense, like a MovingCar is composed of wheels , so if there is a field wheels then it must be initilized along with the creation of object of MovingCar . 如果一个类由很少的字段组成,那么没有该类的对象就没有意义,就像MovingCarwheels组成,因此,如果有一个field wheels则必须在创建MovingCar的对象时对其进行MovingCar These fields better are initilized through Constructors. 这些字段最好通过构造函数初始化。 The other fields such as musicSystem may be initilized using setter methods. 诸如musicSystem类的其他字段可以使用setter方法musicSystem

Sometimes we may end up with so many constructors (overloaded) which may make it confusing for the users of such a class. 有时,我们可能会遇到太多的构造函数(重载),这可能会使此类用户感到困惑。 Methods are better which can be named to let the users know the intention. 可以命名的方法更好,可以让用户知道其意图。 Even better aaproach in such a case is builder pattern . 在这种情况下,甚至更好的方法是builder pattern

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

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