Cannot make a static reference to the non-static

时间:2023-03-08 22:37:03
Cannot make a static reference to the non-static
public class SeckillServiceImpl implements SeckillService{

    private SeckillDao seckillDao;

    private SuccessKilledDao successKilledDao;

    @Override
public List<Seckill> getSeckillList() { return SeckillDao.queryAll(0, 4);
}
}

报错“Cannot make a static reference to the non-static method queryById(long) from the type SeckillDao”

出现这个错误大多是因为弄错了大小写,SeckillDao是一个类名,用类名只能调静态方法,而queryAll()是非静态方法,只能在实例化的对象seckillDao上调用

原因解释:类中静态的方法或者属性,本质上来讲并不是该类的成员,在java虚拟机装在类的时候,这些静态的东西已经有了对象,它只是在这个类中”寄居”,不需要通过类的构造器(构造函数)类实现实例化;而非静态的属性或者方法,在类的装载是并没有存在,需在执行了该类的构造函数后才可依赖该类的实例对象存在。所以在静态方法中调用非静态方法时,编译器会报错(Cannot make a static reference to the non-static method func() from the type A)。