Java的定义或初始化类的属性 [英] Java defining or initializing attributes of a class

查看:221
本文介绍了Java的定义或初始化类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的Java小白。当输入一个新的类,定义类属性时,有没有定义变量和初始化变量的差异。是否有过的情况下,你会想要做一个比其他?我使用了原始的和的情况下,故意对象存在于两种情况下的差异。

 导入了java.util.Random;公共类的东西延伸活动{
    INT整数;
    随机随机= NULL;    东西(){
        整数= 0;
        随机=新的随机();
        ....

VS。
    进口了java.util.Random;

 公共类的东西延伸活动{
    INT整数= NULL;
    随机随机的;    东西(){
        整数= 0;
        随机=新的随机();
        ....


解决方案

首先,你不能设置一个基本为null作为一种原始的仅仅是数据,其中是一个对象参考。如果你试图编译 INT I = NULL 你会得到一个不兼容的类型的错误。

其次初始化的变量或类声明时,其中 0 是多余的,因为在Java中,基元默认为 0 (或)和对象引用默认。这不是局部变量的情况下但是,如果你尝试下面你会得到在编译时初始化错误

 公共静态无效的主要(字串[] args)
 {
     INT I;
     System.out.print(ⅰ);
 }

明确它们初始化为 0 是没有意义的,但你可能想将它们设置为另一种默认值,那么你可以创建具有例如默认值的构造函数

 公共MyClass的
{
   INT theDate = 9;
   字符串日=星期二;   //这将返回类的默认值
   公共MyClass的()
   {
   }   //其中,因为这将返回新的String
   公共MyClass的(字符串aDiffDay)
   {
      天= aDiffDay;
   }
}

Java noob here. When coding a new class, when defining class attributes, is there a difference in defining a variable and initializing a variable. Are there ever cases where you would want to do one over the other? I have used a primitive and an Object on purpose in case there is a difference for either case.

i.e.

import Java.util.Random;

public class Something extends Activity {
    int integer;
    Random random = null;

    Something(){
        integer = 0;
        random = new Random();
        ....

vs. import Java.util.Random;

public class Something extends Activity {
    int integer = null;
    Random random;

    Something(){
        integer = 0;
        random = new Random();
        ....

解决方案

Firstly you cannot set a primitive to be null as a primitive is just data where null is an object reference. If you tried to compile int i = null you would get a incompatible types error.

Secondly initializing the variables to null or 0 when declaring them in the class is redundant as in Java, primitives default to 0 (or false) and object references default to null. This is not the case for local variables however, if you tried the below you would get an initialization error at compile time

 public static void main(String[] args)
 {
     int i;
     System.out.print(i);
 }

Explicitly initializing them to a default value of 0 or false or null is pointless but you might want to set them to another default value then you can create a constructor that has the default values for example

public MyClass
{
   int theDate = 9;
   String day = "Tuesday";

   // This would return the default values of the class
   public MyClass()
   {
   }

   // Where as this would return the new String
   public MyClass (String aDiffDay)
   {
      day = aDiffDay;
   }
}

这篇关于Java的定义或初始化类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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