java中static方法的继承性
首先需要知道的是,java中所有的public实例方法都默认是virtual的,static方法不是virtual的,所以static方法可以被覆盖(new),但不可被重写(override)
1.被继承
父类:
public class Parents{ public static void staticFunction(){ System.out.println("public static function of parents"); } public void callPrintName(){ this.printName(); } }
子类:
1 public class Child extends Parents{ 2 public static void main(String[] args){ 3 Child child=new Child(); 4 child.staticFunction(); 5 } 6 7 }
输出
public static function of parents
说明static方法可以被继承
2.被覆盖(new)
父类:
public class Parents{ public static void staticFunction(){ System.out.println("public static function of parents"); } public void callPrintName(){ this.printName(); } }
子类:
public class Child extends Parents{ public static void staticFunction(){ System.out.println("public static function of Child"); } public static void main(String[] args){ Child child=new Child(); child.staticFunction(); } }
输出:
public static function of Child
上面输出是public static function of Child,说明static已经被覆盖(new)了
3.不是virtual,即不能实重写(override)
//父类 public class Parents{ private void printName(){ System.out.println("private function of parents"); } public static void staticFunction(){ System.out.println("public static function of parents"); } public void callPrintName(){ this.printName(); } } //子类 public class Child extends Parents{ public static void staticFunction(){ System.out.println("public static function of Child"); } public static void main(String[] args){ Parents child=new Child(); child.staticFunction(); } }
输出:
public static function of parents
上面的child是属于Child实例,用Parents引用,输出的是public static function of parents,说明static方法不是virtual的,不能被重写(override)。