我需要帮助创建一个实例变量和构造函数 [英] I need help creating an instance variable and constructors

查看:119
本文介绍了我需要帮助创建一个实例变量和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我知道这个答案很明显,但我想我只是很慢。任何人都可以给我一个实例变量和构造函数的清晰定义?

Sorry, I know this answer is obvious but I suppose I'm just slow. Can anyone give me clear definitions of an instance variable and a constructor?

实例变量:

你的类将需要一个实例变量,一维阵列。数组的大小将由构造函数确定。

Instance variables:
Your class will need an instance variable named numbers that is a one-dimensional array. The size of the array will be determined by the constructor. You may, or may not, find it useful to have other instance variables.

构造函数:

您将编写两个构造函数。
一个构造函数将是一个没有参数的默认构造函数。它将创建一个包含10个int的数组,并将数组的每个元素设置为42.

Constructors:
You will write two constructors. One constructor will be a default constructor that has no arguments. It will create an array that holds 10 int's and will set each element of the array to be 42.

第二个构造函数将接受一个参数,它将是一个数组int。此构造函数将创建与参数相同大小的实例数组,然后将整数从参数复制到实例数组。

The second constructor will take one argument, which will be an array of int. This constructor will create an instance array of the same size as the argument and then copy the integers from the argument to the instance array.

我不知道如何开始。

推荐答案

实例成员只是属于类对象的变量,只要它不是 static 变量!一个静态变量,严格来说属于类不是一个对象,
构造函数只是一个特殊的方法来创建和初始化一个对象。

Instance members are simply variables that belong to a class object, as long as it is not a static variable! A static variable, strictly speaking belongs to the class not an object, Constructors is just a special method you call to create and initialize an object. It is also the name of your class.

所以你想要的是

class WhateverYourClassIs
{
   int[] members;
   public WhateverYourClassIs()//constructor. 
   {
    members = new int[10] ;
    }
   public WhateverYourClassIs(int n) //overloaded constructor.
   {
     members = new int[n] ;
   }
}

正如你在上面的例子中看到的,构造函数像方法一样,可以重载。通过重载意味着签名是不同的。
一个构造函数不带参数,另一个构造函数接受一个int参数。

So as you can see in the above example, constructors like methods, can be overloaded. By overloaded it means the signature is different. One constructor takes no argument, another takes a single argument that is an int.

这篇关于我需要帮助创建一个实例变量和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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