zoukankan      html  css  js  c++  java
  • Java static关键字

    未使用static

    class Test {
        private int age;
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public Test(int age) {
            super();
            this.age = age;
        }
    
    };
    
    public class Static {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            Test t1 = new Test(10);
            System.out.println(t1.getAge());
    
            Test t2 = new Test(11);
            System.out.println(t2.getAge());
        }
    
    }
    //运行结果
    10
    11

    使用static

    class Test {
        static int age; //全局有效
    
        public int getAge() {
            return age;
        }
    
        public static void setAge(int age) { //必须声明static
            Test.age = age; //用类名的方式
        }
    
        public Test(int age) {
            super();
            Test.age = age;
        }
    
    };
    
    public class Static {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            Test t1 = new Test(10);
            Test t2 = new Test(11);
    
            Test.age = 5; //用类名调用
    
            System.out.println(t1.getAge());
            System.out.println(t2.getAge());
        }
    
    }
    //运行结果
    5
    5
  • 相关阅读:
    python反射
    numpy笔记
    leetcode43
    leetcode-42
    The Github Flow
    leetcode-37
    leetcode-41
    leetcode-40
    TCP扫盲2
    字节码分析与操作
  • 原文地址:https://www.cnblogs.com/zhangxuechao/p/11709417.html
Copyright © 2011-2022 走看看