构造函数 Constructors in Java – A complete study!!

Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.

  • 构造函数是一个初始化新创建对象的代码块。构造函数类似于java中的实例方法,但它不是一个方法,因为它没有返回类型。简而言之,构造函数和方法是不同的(本指南末尾有更多内容)。人们经常在Java中将构造函数称为特殊类型的方法

Constructor has same name as the class and looks like this in a java code.

  • 构造函数与类具有相同的名称,在java代码中看起来像这样。
public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

Note that the constructor name matches with the class name and it doesn’t have a return type. 

  • 请注意,构造函数名称与类名称匹配,并且它没有返回类型

How does a constructor work

To understand the working of constructor, lets take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:

MyClass obj = new MyClass()

 The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object.

  • new关键字在这里创建类MyClass的对象,并调用构造函数来初始化这个新创建的对象。 

 You may get a little lost here as I have not shown you any initialization example, lets have a look at the code below:

你可能会在这里迷惑,因为我没有向你展示任何初始化示例,让我们看看下面的代码: 

A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the instance variable nameof the object. As you can see that the output is BeginnersBook.com which is what we have passed to the name during initialization in constructor. This shows that when we created the object obj the constructor got invoked. In this example we have used this keyword, which refers to the current object, object obj in this example. We will cover this keyword in detail in the next tutorial.

这里我们创建了一个Hello类的对象obj,然后我们显示了该对象的实例变量名。正如您所看到的那样,输出是BeginnersBook.com,这是我们在构造函数初始化期间传递给名称的内容。这表明当我们创建对象obj时,调用了构造函数。在这个例子中,我们使用了这个关键字,它引用了当前对象,在这个例子中是对象obj。我们将在下一个教程中详细介绍此关键字。 

public class Hello {
   String name;
   //Constructor
   Hello(){
      this.name = "BeginnersBook.com";
   }
   public static void main(String[] args) {
      Hello obj = new Hello();
      System.out.println(obj.name);
   }
}

Output:

BeginnersBook.com

 补充:使用static修饰的成员变量是类变量,属于该类本身;没有使用static修饰的成员变量是实例变量,属于该类的实例。

new keyword invoked the constructor 

初始化对象MyClass的同时,调用构造器; 

Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.

构造函数有三种类型:Default,No-arg构造函数和Parameterized。

types of constructor

Default constructor

If you do not implement any constructor in your class, Java compiler inserts a default constructorinto your code on your behalf. This constructor is known as default constructor. You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file. This process is shown in the diagram below:

 默认构造函数如果未在类中实现任何构造函数Java编译器将代表您的代码插入默认构造函数。此构造函数称为默认构造函数。您不会在源代码(java文件)中找到它,因为它将在编译期间插入到代码中并存在于.class文件中。此过程如下图所示:

default constructor 

If you implement any constructor then you no longer receive a default constructor from Java compiler.

如果实现任何构造函数,则不再从Java编译器接收默认构造函数。

no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.

没有参数的构造函数称为no-arg构造函数。签名与默认构造函数相同,但是body可以具有任何代码而不像构造函数的主体为空的默认构造函数。

Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it.

虽然您可能会看到有些人声称默认和无参数构造函数是相同的,但实际上它们不是,即使您在类Demo中编写公共Demo(){}也不能将其称为默认构造函数,因为您已经编写了代码它的。 

Example: no-arg constructor

class Demo
{
     public Demo()
     {
         System.out.println("This is a no argument constructor");
     }
     public static void main(String args[]) {
    	 new Demo();
     }
}

Output:
This is a no argument constructor

初始化对象Demo的同时,调用构造器;  

 可以参考head first java 242 页 帮助理解;

Parameterized constructor 参数构造函数

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

带参数的构造函数(或者您可以说参数)称为参数化构造函数。

Example: parameterized constructor

In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2.

在这个例子中,我们有一个带有两个参数id和name的参数化构造函数。在创建对象obj1和obj2时,我传递了两个参数,以便在创建obj1和obj2之后调用此构造函数。

public class Employee {

   int empId;  
   String empName;  
	    
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
	   
   public static void main(String args[]){  
	Employee obj1 = new Employee(10245,"Chaitanya");  
	Employee obj2 = new Employee(92232,"Negan");  
	obj1.info();  
	obj2.info();  
   }  
}

Output:

Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Example2: parameterized constructor 

What if you implement only parameterized constructor in class

class Example3
{
      private int var;
      public Example3(int num)
      {
             var=num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example3 myobj = new Example3();
              System.out.println("value of var is: "+myobj.getValue());
      }
}

Output: It will throw a compilation error. The reason is, the statement Example3 myobj = new Example3() is invoking a default constructor which we don’t have in our program. when you don’t implement any constructor in your class, compiler inserts the default constructor into your code, however when you implement any constructor (in above example I have implemented parameterized constructor with int parameter), then you don’t receive the default constructor by compiler into your code.

输出:它将抛出编译错误。原因是,语句Example3 myobj = new Example3()正在调用我们程序中没有的默认构造函数。当您没有在类中实现任何构造函数时,编译器会将默认构造函数插入到您的代码中但是当您实现任何构造函数时(在上面的示例中,我已经使用int参数实现了参数化构造函数),那么您不会收到默认构造函数通过编译器进入你的代码。 

If we remove the parameterized constructor from the above code then the program would run fine, because then compiler would insert the default constructor into your code.

如果我们从上面的代码中删除参数化构造函数,那么程序运行正常(输出为0),因为编译器会将默认构造函数插入到代码中

Constructor Chaining 构造器连接

When A constructor calls another constructor of same class then this is called constructor chaining. Read more about it here.

 当构造函数调用同一个类的另一个构造函数时,这称为构造函数链接。

constructor chaining

Refer constructor overloading with example for more details with example.  参考构造器重载

Super()

Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You can also say that the compiler inserts a super(); statement at the beginning of child class constructor.

 每当调用子类构造函数时,它都会隐式调用父类的构造函数。你也可以说编译器插入了一个super();子类构造函数开头的语句。

public class Employee {
    public String empName;
    public int empSalary;
    public String address;

    //default constructor of the class
    public Employee()
    {
        //this will call the constructor with String param
        this("Chaitanya");
    }

    public Employee(String name)
    {
        //call the constructor with (String, int) param
        this(name, 120035);
    }
    public Employee(String name, int sal)
    {
        //call the constructor with (String, int, String) param
        this(name, sal, "Gurgaon");
    }

    public Employee(String name, int sal, String addr)
    {
        this.empName=name;
        this.empSalary=sal;
        this.address=addr;
    }

    void disp() {
        System.out.println("Employee Name: "+empName);
        System.out.println("Employee Salary: "+empSalary);
        System.out.println("Employee Address: "+address);
    }
    public static void main(String[] args)
    {
        Employee obj = new Employee();
        obj.disp();
    }


}

Java Copy Constructor

A copy constructor is used for copying the values of one object to another object.

复制构造函数用于将一个对象的值复制到另一个对象。 

class JavaExample{  
   String web; 
   JavaExample(String w){  
	web = w;
   }  

   /* This is the Copy Constructor, it 
    * copies the values of one object
    * to the another object (the object
    * that invokes this constructor)
    */
   JavaExample(JavaExample je){  
	web = je.web; 
   }  
   void disp(){
	System.out.println("Website: "+web);
   }  

   public static void main(String args[]){  
	JavaExample obj1 = new JavaExample("BeginnersBook");  
		
	/* Passing the object as an argument to the constructor
	 * This will invoke the copy constructor
	 */
	JavaExample obj2 = new JavaExample(obj1);  
	obj1.disp();  
	obj2.disp();  
   }  
}

 Output:

Website: BeginnersBook
Website: BeginnersBook

Constructor Overloading

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.

构造函数重载是一个具有多个具有不同参数列表的构造函数的概念,以这种方式使每个构造函数执行不同的任务

constructor overloading 

Refer constructor overloading with example for more details with example.

Java Copy Constructor

A copy constructor is used for copying the values of one object to another object.

Quick Recap

Every class has a constructor whether it’s a normal class or a abstract class.

每个类都有一个构造函数,无论它是普通类还是抽象类。

Constructors are not methods and they don’t have any return type.  构造函数不是方法,它们没有任何返回类型。

Constructor name should match with class name .构造函数名称应与类名匹配。

Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.

构造函数可以使用任何访问说明符,也可以将它们声明为私有。私有构造函数在java中是可能的,但是范围只在类中。

Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.

 像构造函数一样,方法也可以具有与类名相同的名称,但它们仍然具有返回类型,尽管我们可以识别它们是方法而不是构造函数。

If you don’t implement any constructor within the class, compiler will do it for.

如果你没有在类中实现任何构造函数,编译器将会为你构造。

this() and super() should be the first statement in the constructor code. If you don’t mention them, compiler does it for you accordingly.

this()和super()应该是构造函数代码中的第一个语句。如果您不提及它们,编译器会相应地为您执行此操作。

Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.

构造函数重载是可能的,但是无法覆盖。这意味着我们可以在类中重载构造函数,但是我们不能覆盖构造函数。

Constructors can not be inherited.构造函数不能被继承。 

If Super class doesn’t have a no-arg(default) constructor then compiler would not insert a default constructor in child class as it does in normal scenario.

如果Super类没有no-arg(默认)构造函数,那么编译器不会像在正常情况下那样在子类中插入默认构造函数。

Interfaces do not have constructors.接口没有构造函数。

Abstract class can have constructor and it gets invoked when a class, which implements interface, is instantiated. (i.e. object creation of concrete class).抽象类可以有构造函数,当实现接口的类被实例化时,它会被调用。(即具体类的对象创建)。

A constructor can also invoke another constructor of the same class – By using this(). If you want to invoke a parameterized constructor then do it like this: this(parameter list).

构造函数也可以调用同一个类的另一个构造函数 - 使用this()。如果要调用参数化构造函数,则执行以下操作:this(参数列表)。

来自:https://beginnersbook.com/2013/03/constructors-in-java/

猜你喜欢

转载自blog.csdn.net/nsjlive/article/details/89504734