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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 楼夜雪 中级黑马   /  2015-10-2 09:49  /  820 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package day08;

public class Grade1Student extends Student{
        private String name;
        private int age;
        private String sex;
        private String School;
        private static int grade;
        public Grade1Student() {
                super();
                // TODO Auto-generated constructor stub
        }
        public Grade1Student(String name, int age, String sex, String name2,
                        int age2, String sex2, String school, int grade) {
                super(name, age, sex, name2, age2, sex2, school, grade);
                // TODO Auto-generated constructor stub
        }
        public Grade1Student(String name, int age, String sex) {
                super(name, age, sex);
                // TODO Auto-generated constructor stub
        }
        public Grade1Student(String name, int age) {
                super(name, age);
                // TODO Auto-generated constructor stub
        }
        public Grade1Student(String name, int age, String sex, String school) {
                super();
                this.name = name;
                this.age = age;
                this.sex = sex;
                School = school;//静态变量没有this关键字
        }
        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }
        public String getSex() {
                return sex;
        }
        public void setSex(String sex) {
                this.sex = sex;
        }
        public String getSchool() {
                return School;
        }
        public void setSchool(String school) {
                School = school;
        }
        public static int getGrade() {
                return grade;
        }
        public static void setGrade(int grade) {
                Grade1Student.grade = grade;
        }
}
//我想创建一个四年级的学生类,于是把年级定义成静态
但是eclipse自动给出的Gradeget set方法也是静态的,但是报错了 为什么?
方法去掉static之后就OK了
这是在同一个类里面  而且都是静态的 为什么会报错啊 静态调用静态 思想没错吧

4 个回复

倒序浏览
大神告诉我为什么
回复 使用道具 举报
66666666666666666666666666666666666666666666666666
回复 使用道具 举报
你上面写的SetGrade()方法是可以静态的,而且你去掉static也是没错的!这可以从他们在内存中的加载顺序就可以知道的,static变量和方法是在方法区中并且优先于对象存在的,而实类变量在这个时候还不存在,所以static方法只能访问静态变量;非static方法可以访问static变量,是因为这个时候对象已经存在了,故可以直接访问静态了。
回复 使用道具 举报
=-= 你为啥非得写成静态的呀 ..
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马