CodeGym学习第三天:static变量与非static变量

static变量

如果变量被声明为 static,即标记有关键字 static,则它在类存在期间一直存在。JVM (Java虚拟机)通常在首次使用类时将其加载到内存中。static 变量也是在此时进行初始化的。
在这里插入图片描述
上图中的Cat 类包含4个变量,其中count变量被声明为static变量,由类的所有对象共享,可称作是类变量。而a、b、s为非static变量,每个实例中可以存在不同的值,可称作实例变量。由于static变量是所有对象所共享的,所以在使用时需要在变量名前面加上类名,如Cat.count。而非static变量是每个实例所独有的,在使用时需要在变量名前面加上this。如this.a。

实战演习

import java.io.*;
class test  
{
   public static void main(String[] args) {
       //创建Apple实例,并调用addPrice方法
        Apple apple1 = new Apple();
        apple1.addPrice(50);
        Apple apple2 = new Apple();
        apple2.addPrice(100);
        //输出结果
        System.out.println("苹果1的价格为 " + apple1.applePrice);
        System.out.println("苹果2的价格为 " + apple2.applePrice);
        System.out.println("苹果的总价格为 " + Apple.sum);
        
    }
    //创建一个Apple类
    public static class Apple {
        public static int sum = 0; 						//所有苹果的总价格
        int applePrice;          						//该苹果的价格
        public void addPrice(int applePrice) { 
            this.applePrice = applePrice; 				//设置苹果价格 
            Apple.sum += applePrice;       				//设置苹果总价 
        }
    }
}

在上述代码中,创建了Apple类,声明了两个变量:sum(static变量)、applePrice(非static变量)。在编写addPrice方法时,使用 this.applePrice = appPrice 语句为实例变量applePrice赋值,使用 Apple.sum += applePrice 为类变量sum赋值。
输出结果为:
苹果1的价格为 50
苹果2的价格为 100
苹果的总价格为 150

总结

在调用类中的static变量时,使用类名.变量名;在调用类中的非static变量时,使用this.变量名

原创文章 2 获赞 1 访问量 215

猜你喜欢

转载自blog.csdn.net/Y_HF12138/article/details/105895913
今日推荐