码迷,mamicode.com
首页 > 编程语言 > 详细

Java学习——使用Static修饰符

时间:2018-10-13 19:45:38      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:stat   gety   分享   todo   不可   原来   new   bsp   demo   

这是原来的

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

技术分享图片

 

Java学习——使用Static修饰符

标签:stat   gety   分享   todo   不可   原来   new   bsp   demo   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!