Java构造函数链接 [英] Java Constructor Chaining

查看:89
本文介绍了Java构造函数链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学习Java中的构造函数链接,并且有一些疑问...

Hi I am just learning about constructor chaining in Java and had some questions...

  1. 首先有人可以解释一下我何时需要使用它吗?从头顶上我真的无法想到一种情况.

  1. First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.

在此示例中,在没有参数的构造函数中,我调用了另一个构造函数.如何访问这个新的詹姆斯·邦德"对象以备将来使用?

In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?

import java.util.*;

class Employee
{   
    private String name;
    private double salary;

    public Employee()
    {
        this("James Bond", 34000);
    }

    public Employee(String n, double s)
    {
        name = n;
        salary = s;
    }

    public String getName()
    {
        return name;
    }

    public double getSalary()
    {
        return salary;
    }

    public static void main(String[] args)
    {
        Employee a = new Employee();
    }
}

推荐答案

实际上,我相信链式构造函数的最常见用法是构造函数所做的不仅仅是设置成员变量.

Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.

static int numOfExamples = 0;
public Example(String name, int num)
{
    this.name = name;
    this.num = num;
    numOfExamples++;
    System.out.println("Constructor called.");
    Log.info("Constructor called");
}

public Example()
{
    this("James Bond",3);
}

这样,我们不必编写两次记录和递增静态变量的代码,而只需链接构造函数即可.

That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.

这篇关于Java构造函数链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆