java类的类属性初始化,Java的定义或初始化类的属性

本文讨论了在Java中定义类属性时,变量声明与初始化的区别。虽然基本类型的变量会默认为0,对象引用默认为null,但显式初始化可以在构造器中设定默认值或提供更具体的初始状态。初始化为特定值可以避免潜在的NullPointerException,并有助于代码的清晰性。
摘要由CSDN通过智能技术生成

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值