• Java学习——使用Static修饰符


    这是原来的

    class StaticDemo {
    static int x;
    int y;
    public static int getX() {
    return x;//静态方法中可以访问静态数据成员x
    }
    public static void setX(int newX) {
    x = newX;
    }
    public int getY() {//int 前加static试试(静态方法中不可以访问非静态数据成员y)
    return y;// 非静态方法中可以访问非静态数据成员y
    }
    public void setY(int newY) {//试试增加 x=20; 非静态方法中可以访问静态数据成员x
    y = newY;
    }
    }
    public class LX4_1 {
    public static void main(String[] args) { 
        System.out.println("静态变量 x="+StaticDemo.getX());
    System.out.println("实例变量 y="+StaticDemo.getY());//非法,编译将出错
             StaticDemo a= new StaticDemo(); 
             StaticDemo b= new StaticDemo();
             a.setX(1);
             a.setY(2);
             b.setX(3); b.setY(4);
    System.out.println("静态变量 a.x="+a.getX());
             System.out.println("实例变量 a.y="+a.getY()); 
             System.out.println("静态变量 b.x="+b.getX()); 
             System.out.println("实例变量 b.y="+b.getY());
    }
    }

    这是修改以后的

    package hello;
    
    public class 使用Static修饰符 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("静态变量 x=" + StaticDemo.getX());
            System.out.println("实例变量 y=" + StaticDemo.getY());// 非法,编译将出错
            StaticDemo a = new StaticDemo();
            StaticDemo b = new StaticDemo();
            a.setX(1);
            a.setY(2);
            b.setX(3);
            b.setY(4);
            System.out.println("静态变量 a.x=" + a.getX());
            System.out.println("实例变量 a.y=" + a.getY());
            System.out.println("静态变量 b.x=" + b.getX());
            System.out.println("实例变量 b.y=" + b.getY());
        }
    
    }
    
    class StaticDemo {
        static int x;
        static int y;
    
        public static int getX() {
            return x;// 静态方法中可以访问静态数据成员x
        }
    
        public static void setX(int newX) {
            x = newX;
        }
    
        public static int getY() {// int 前加static试试(静态方法中不可以访问非静态数据成员y)
            return y;// 非静态方法中可以访问非静态数据成员y
        }
    
        public static void setY(int newY) {// 试试增加 x=20; 非静态方法中可以访问静态数据成员x
            y = newY;
        }
    }

  • 相关阅读:
    python內建模块之datetime
    python实现两个经纬度点之间的距离和方位角
    Python实现DBScan
    关于sru源码class Model的parameters
    pytorch之LSTM
    pytorch对可变长度序列的处理
    pytorch函数之torch.normal()
    PyTorch学习系列(九)——参数_初始化
    ubuntu16.04系统搜狗输入法的安装
    Scala 匿名函数
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13270859.html
Copyright © 2020-2023  润新知