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;
    }
}

原文地址:https://www.cnblogs.com/caiyishuai/p/13270859.html