super与this无法用在static方法中,
分享于 点击 18990 次 点评:230
super与this无法用在static方法中,
更新记录
【1】2020.02.08--10:32
1.主要编辑了super
正文
我原本是在学习\(super\)关键字,后来突发奇想,能不能在父类中用\(super\)间接调用本类方法呢?
也就是说父类的方法(假设方法名为\(printData\)),通过子类的\(super\)去间接调用。
于是,就有了这样的一段代码:
class ChildClass extends Class2{
public static void print() {
super.printData();
}
}
public class Class2 {
protected void printData() {
System.out.println("调用父类printData方法");
}
public static void main(String[] args) {
ChildClass.print();
}
}
结果出现这样一段错误:Cannot use super in a static context
原因非常清楚。
我又写了一段代码:
class ChildClass extends Class2{
public void printData() {
super.printData();
}
}
public class Class2 {
protected void printData() {
System.out.println("调用父类printData方法");
}
public static void main(String[] args) {
new ChildClass().printData();
}
}
运行结果:调用父类printData方法
反过头来,为什么不可以在\(static\)方法中使用\(super\)呢
看看\(static\)方法有什么性质
它是静态方法
静态?
会随着类的定义而被分配和装载入内存中。
而且它是类方法,类方法是属于整个类的,用类名去调用。
有了上述了解,配合下面的代码就会理解
class ChildClass extends Class2{
public static void printData() {
//super.XXX();
}
}
public class Class2 {
public static void main(String[] args) {
ChildClass.printData();
}
}
看看编译时\(super\)去调用谁呢
静态方法先存在,然后对象再存在,所以编译静态方法时,对象还没出现
此时\(super\)指向的是空,当然不被编译器认可,\(this\)也是同理
相关文章
- 暂无相关文章
用户点评