Java中的引用变量
时间:2020-02-23 14:35:32 来源:igfitidea点击:
在本教程中,我们将在Java中看到引用变量。
引用变量
包含对象引用的变量被称为 reference variable(引用变量)。
变量是一个名称,用于在程序执行期间保持任何类型的值。
如果类型是对象,则变量称为引用变量,如果该变量保存基本类型(int,float等),则它被称为非引用变量。
例如,如果我们创建一个可容纳的变量 String对象,然后它被称为引用变量,因为 String是一个类。
看到一个例子。
String str = "theitroad"; //str is reference variable MyClass mCl = new MyClass(); //mCl is reference variable int a = 10; //non-reference variable
引用变量基本上指向存储到堆内存中的对象。
Note: Default value of a reference variable always a null.
我们可以创建内置类或者用户定义类的引用变量。
Java提供了数百个内置的类 String那 ArrayList那 Arrays那 Math等等,我们可以创建这些类的引用并调用其成员字段和方法。
除了内置类对象外,我们可以创建我们的自定义(用户定义)类的参考。
例如,我们创建了一个类 MyClass并创建了一个引用变量 myClass在里面抓住它的物体 Demo类。
class MyClass{
void showMyName(String name) {
System.out.println("Your name is "+name);
}
}
public class Demo {
public static void main(String[] args){
//Creating reference to hold object of MyClass
MyClass myClass = new MyClass();
myClass.showMyName("theitroad");
}
}
输出:
Your name is theitroad
基于其范围和可访问性,引用变量可以是许多类型的。
例如,
- 静态引用变量
- 实例引用变量
- 本地引用变量
静态引用变量
一个 variable使用静态关键字定义称为静态变量。
静态变量也可以是参考或者非引用。
在此示例中,我们创建了两个静态引用变量并在Main()方法中访问它们。
public class Demo {
//Static reference variables
static String str;
static String str2 = "theitroad";
public static void main(String[] args){
System.out.println("Value of str : "+str);
System.out.println("Value of str2 : "+str2);
}
}
输出
Value of str : null Value of str2 : theitroad
实例引用变量
一个 variable在程序中没有静态和定义,称为一个 instance reference variable。
由于实例变量属于对象,因此我们需要使用引用变量来调用实例变量。
public class Demo {
//instance reference variables
String str;
String str2 = "theitroad";
public static void main(String[] args){
Demo demo = new Demo();
System.out.println("Value of str : "+demo.str);
System.out.println("Value of str2 : "+demo.str2);
}
}
输出
Value of str : null Value of str2 : theitroad
本地引用变量
Reference variable可以声明为 local变量。
例如,我们在Main()方法中创建了字符串类作为本地引用变量。
public class Demo {
public static void main(String[] args){
//Local reference variables
String str2 = "theitroad";
System.out.println("Value of str2 : "+str2);
}
}
输出:
Value of str2 : theitroad

