Java 为什么要创建类类型的变量?
我们可以用于创建对象的第一行,在哪个场景中我们可以使用2和3 测试=新测试; Test=null; 试验;Java 为什么要创建类类型的变量?,java,Java,我们可以用于创建对象的第一行,在哪个场景中我们可以使用2和3 测试=新测试; Test=null; 试验; 第一种方法实际上创建了一个名为Test的实例,并将其分配给变量Test Test test =new Test(); // ' ; ' missing 第二个只为测试分配一个空指针 Test test =null; 第三种方法不会为测试分配任何内容,除非它是一个实例变量,在这种情况下,它将为它分配一个null值 Test test ; 显然,您不知道以下创建对象的方法,因为只有一种方
第一种方法实际上创建了一个名为Test的实例,并将其分配给变量Test
Test test =new Test(); // ' ; ' missing
第二个只为测试分配一个空指针
Test test =null;
第三种方法不会为测试分配任何内容,除非它是一个实例变量,在这种情况下,它将为它分配一个null值
Test test ;
显然,您不知道以下创建对象的方法,因为只有一种方法确实知道,假设添加了正确的分号以允许行编译
Test test = new Test();
这是用直接Java语法实际创建对象的唯一方法。对象创建可以通过在幕后使用new关键字的方法进行模糊处理,但它可以归结为使用new关键字和构造函数调用
Test test = null;
将此变量设置为null只会为名为Test的测试对象创建一个holder。但是null不是一个对象,并且没有创建任何内容
Test test;
此行的作用与在类中将test设置为null相同,但在方法中,它允许持有者的声明允许在下一行中设置它。但是,如果Java编译器无法在进一步的代码中读取该变量之前找出您实际设置该变量的路径,则会出现语法错误。要避免此错误,可以像前一行一样在开始时将其设置为null
Test test;
在本例中,未生成对象。这只会在堆栈中创建测试变量。它的类型是测试对象类型
Test test=null;
在本例中,您为该引用分配空值
Test test =new Test();
这意味着,您在类测试中装入新对象。此对象在堆中生成
我认为这是java最基本的东西。你需要做进一步的研究。
多谢各位
public class Test{
int a ;
public Test(){
}
public class Test(int a){
this.a = a ;
}
public static void main(String args[]){
//To define a variable of type Test
Test t ;
//Defining another variable of type Test
Test t2;
//To instantiate an object of type Test using no argument constructor
//Now t holds a reference to object created by new Test()
t = new Test();
//Pass the Object reference in t to t2 variable
t2 = t ;
//To instantiate an object using one argument constructor Test(int a)
//Now t will hold reference to object created by new Test( 2)
//That makes old Test instance created by no argument constructor eligible to be cleanedup by garbage collector
t= new Test(2);
//now to release the reference to object created by new Test(2) , we set null
//In better words, we are setting the reference to "null", so that variable t no longer point to the test instance"
//For better understanding, search for database/JDBC programming example to see how we use "null" in finally block
t = null;
}
通常,null用于取消引用特定变量引用的任何对象。您指的是哪本书学习Java?没有一本书解释上述场景……您的文档在发行行中不正确。考虑下面的编辑:测试t2= t;t=零;好的,Metroid:我只是想让他明白,在大多数OOPS语言中,构造函数方法与new一起用于在Java中创建对象,null用于解引用。顺便说一句,我是个新手,不知道哪里出了问题。为什么我们需要T2?PS:我知道我犯了很多愚蠢的错误,我很乐意纠正meIt的错误,真的,但是有人可能会认为这是释放内存,而不是将引用设置为不再指向测试实例。从技术上讲,您也发布了对新测试的引用,但您没有记录它。我跳了枪,道歉。不需要道歉,兄弟,我知道你只是想让我的帖子更好。我会改正我的错误。谢谢,再见