A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© fyg408224345 中级黑马   /  2015-6-12 21:14  /  9371 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

静态变量可以写setget方法吗?下面是我写的代码。
class Person{
        //属性
        private String name;
        static int age;

        //构造器
        public Person(){}
        public Person(String name, int age){
                this.name = name;
                this.age = age;
        }
       
        //setget方法
        public void setName(String name){
                this.name = name;
        }
        public String getName(){
                return name;
        }

        public /*static*/ void setAge(int age){             //这里如果不去掉static的话会报错:无法从静态上下文中引用非静态变量  this
                this.age = age;                                                                   this.age = age
        }                                                                                                    ^
        public static int getAge(){
                return age;
        }
        //方法
        public void eat(){
        }

}

我想问的是那个setAge()和getAge()算静态方法吗?算age的get set方法吗?为什么会报错啊。
下面的getAge()方法用static修饰不会报错。setAge()方法为什么会报错?求大神指点。

5 个回复

倒序浏览
getAge()与setAge()你用静态修饰了就是静态。
你出错是因为你在静态方法中使用this关键字。this代表其所在方法所属对象的引用,是在创建对象后使用的。你用static修饰方法,随着类的加载而加载,没创建对象,那就无法使用this关键字。
回复 使用道具 举报
静态变量是随着类的加载而加载的,是在内存的方法区中的静态去。有默认初始值。 只能赋值一次。不能有get()方法
回复 使用道具 举报
static不能使用关键字this啊
回复 使用道具 举报
Overheat 发表于 2015-6-12 22:08
getAge()与setAge()你用静态修饰了就是静态。
你出错是因为你在静态方法中使用this关键字。this代表其所在 ...

是不是静态变量不用写setget方法,访问直接  类名.静态变量名就可以,不用写setget?
回复 使用道具 举报
this是属于对象的。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马