【Java】static变量和非static变量调用的区别

本文通过示例讲解了Java中static变量和非static变量的使用区别。对于static变量,需通过类名调用来修改和访问,如`Apple.applePrice`;而非static变量(实例变量)则使用`this`关键字,如`this.age`。示例展示了如何在不同对象间共享static变量的值,并强调了在类方法中直接操作static变量的特性。
摘要由CSDN通过智能技术生成

static变量调用是使用 类名.变量名 的格式从而修改静态变量的值。
例:
若是使用以下方法将会输出“苹果的价格为150”

public class Solution {

    public static void main(String[] args) {
        Apple apple = new Apple();
        apple.addPrice(50);
        Apple apple2 = new Apple();
        apple2.addPrice(100);
        System.out.println("苹果的价格为 " + Apple.applePrice);
    }

    public static class Apple {
        public static int applePrice = 0;

        public static void addPrice(int applePrice) {
            Apple.applePrice=Apple.applePrice+applePrice;
        }
    }
}

若前面不加上 Apple. 则会输出“苹果的价格为0”

关于非static变量,则使用时使用this调用即可,例如:

public class Solution {

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("年龄:" + person.age);
        person.adjustAge(person.age);
        System.out.println("调整后的年龄:" + person.age);
    }

    public static class Person {
        public int age = 20;

        public void adjustAge(int age) {
            this.age = age + 20;
            System.out.println("adjustAge() 中的年龄为 " + this.age);
        }
    }
}

其运行结果为:
在这里插入图片描述

总结:

  1. 非static用this.变量名
  2. static用类名.变量名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值