为什么使用构造函数,为什么不总是使用简单的变量初始化? [英] why constructor use, why not always use simple initialization of variables?

查看:48
本文介绍了为什么使用构造函数,为什么不总是使用简单的变量初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了很多,并在堆栈溢出时得到了这个答案在此处给出答案

I have searched about this lot and get this answer on stack overflow given answer here

  • 声明我们可以同时使用构造函数和简单初始化

但是我想要这个答案

  • 但是,如果编译器自动完成构造函数初始化,为什么还要使用构造函数初始化!

推荐答案

构造函数的简单定义:

初始化类对象的特殊方法.始终且仅与 new 关键字一起使用以创建类的实例.

Special methods that initialize an object of a class. Always and only used together with the new keyword to create an instance of a class.

  1. 具有与班级名称相同的名称.
  2. 可以接受一个或多个参数.
  3. 没有返回值,甚至没有空.
  4. 默认构造函数不带任何参数.
  5. 存在多个构造函数(方法重载).

但是为什么要使用构造函数初始化,如果它是自动完成的编译器!

but why use constructor initialization if it automatically done by compiler !

构造函数由编译器(默认构造函数)初始化,如果您尚未实现构造函数.

那为什么我们需要实现一个构造函数呢?

So why do we need to implement a constructor?

  • 它的工作是告诉所有局部变量其初始值,并可能在类中开始另一个方法来做一些更符合课堂目的的东西.
  • 取决于您拥有的数据,即可用的数据.
  • 创建对象的不同方式.
  • 所有类变量都必须使用构造函数进行初始化.

例如:

  • 考虑 java.awt 包中的 Rectangle 类,该包提供了几个不同的构造函数,都命名为 Rectangle(),但是每个参数具有不同数量的参数,或者具有不同类型的参数,新的 Rectangle 对象将从中获取其初始状态.这是来自 java的构造函数签名.awt.Rectangle 类:

  • Consider the Rectangle class in the java.awt package which provides several different constructors, all named Rectangle(), but each with a different number of arguments, or different types of arguments from which the new Rectangle object will get its initial state. Here are the constructor signatures from the java.awt.Rectangle class:

公共Rectangle()

如果您的成员变量是 private (出于安全原因)怎么办?如果不想给其他类处理成员变量,则必须使用getter和setter,但是首先可以使用构造函数对其进行初始化,然后可以在以后需要时使用getter和setter对其进行更改.进行更改/更新.

What if your member variables are private (security reasons)? If you do not want to give other classes to handle member variables, you have to use getters and setters, but in the first place, you can initialize it with a constructor, then you can change it using getters and setters later on when you need to change/update it.

这篇关于为什么使用构造函数,为什么不总是使用简单的变量初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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