首页 > 编程语言 > 详细

java中的static关键字

时间:2020-09-15 20:55:24      阅读:75      评论:0      收藏:0      [点我收藏+]

static关键字的作用可理解为静态属相, 如静态变量, 静态方法, 即直接使用类名来访问, 虽然使用对象调用也能执行, 但不建议这么用;

不使用static修饰的变量或方法都只能使用对象调用(python类中定义的都默认是对象方法)

 

1. 使用static修饰的变量

public class ClassTest {

    public static void main(String[] args) {
        User obj = new User();
//        obj.func();  使用对象调用static修饰的func, 虽也能执行, 但不建议这么做
        User.func();
        System.out.println(User.i);
//        System.out.println(User.x);    此处的x没有使用static修饰, 不能用类名来调用
        System.out.println(obj.x);    // 使用对象调用
    }

}


class User{
    static int i = 10;
    int x = 10;

    public static void func() {
        System.out.println("run func......");
        System.out.println(User.i);
//        System.out.println(User.x);    此处的x没有使用static修饰, 不能用类名来调用
    }
}

 

java中的static关键字

原文:https://www.cnblogs.com/quzq/p/13675235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!