栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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用类名.变量名
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287599.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号