DESKTOP-7O1P1F7_20200826-齐元朝
static修饰的成员能不能被继承
在学习继承重写的时候,我们知道,父类中的static修饰的类方法,不可以被子类重写,只能说子类的同名方法隐藏了父类中的同名方法,一旦在子类同名方法上面加上 @Override 则编译器会报错,此时,我们认为父类中的static成员不能被继承
但是,如果子类没有继承父类的static成员,那么,子类中就不会有父类中static的变量和方法,同时我们能也知道,this是对象内部指向对象本身,就是对象自身的引用变量,那么this是不能访问/调用static成员的,但是在程序中是可以的
有一个父类如下:
public class Six {
int f=0;
static int g=2;
public static void d() {
System.out.println("沙悟净");
}
}
一个子类继承了该父类:
public class Sixtest extends Six {
Sixtest(int a,int b){
super();
this.f=a;
this.g=b; //The static field Six.g should be accessed in a static way
}
void l() {
this.d(); //The static method d() from the type Six should be accessed in a static way
}
public static void main(String[] args) {
Sixtest s=new Sixtest(5,5);
}
}
在上面子类中,子类构造中this访问到了static修饰的g变量,在l方法中,也通过this调用到了static修饰的d方法,如果子类没有继承父类中static成员,那么子类中g和d是怎么来的?
点赞