package cn.StaticDemo01;
public class BaseClass {
public void methodOne(){
System.out.println("The methodOne in BaseClass");
}
public void methodTwo(){
System.out.println("The methodTwo in BaseClass");
}
public static void methodThree(){
System.out.println("The methodThree in BaseClass");
}
public static void methodFour(){
System.out.println("The methodFour in BaseClass");
}
}
package cn.StaticDemo01;
public class DerivedClass extends BaseClass {
/*
静态方法只能被继承,不能被重写。子类中可以定义与父类相同的静态方法,此时只是将父类的方法隐藏,而不是覆盖它
*/
//重写,覆盖
public /*static*/ void methodOne(){
System.out.println("The methodOne in DerivedClass");//将父类中的非静态成员方法变成静态的
}
//重写,覆盖
public void methodTwo(){
System.out.println("The methodTwo in DerivedClass");
// super.methodTwo();
}
/*public void methodThree(){
System.out.println("The methodThree in Derived Class");//将父类中的静态成员方法改成非静态的
}*/
//隐藏
public static void methodThree(){ System.out.println("The methodThree in DerivedClass"); }
//隐藏
public static void methodFour(){ System.out.println("The methodFour in DerivedClass"); }
}
package cn.StaticDemo01;
public class StaticTest {
public static void main(String[] args){
BaseClass bc=new BaseClass();
DerivedClass dc=new DerivedClass();
bc.methodOne(); //The methodOne in BaseClass
bc.methodTwo(); //The methodTwo in BaseClass
BaseClass.methodThree(); //The methodThree in BaseClass
BaseClass.methodFour(); //The methodFour in BaseClass
dc.methodOne(); //The methodOne in Derived Class
dc.methodTwo(); //The methodTwo in Derived Class
dc.methodThree(); //The methodThree in Derived Class
DerivedClass.methodFour(); //The methodFour in Derived Class
BaseClass bc2 = new DerivedClass();
发生隐藏时,不会出现动态绑定
bc2.methodThree(); //The methodThree in BaseClass
bc2.methodFour(); //The methodFour in BaseClass
//重写了父类的方法,发生多态
bc2.methodOne(); //The methodOne in DerivedClass
bc2.methodTwo(); //The methodTwo in Derived Class
}
}
结果:
静态方法只能继承,不能重写。子类中可以定义与父类相同的静态方法,此时只是将父类中的方法隐藏,而不是覆盖它。
隐藏:隐藏:父类和子类拥有相同名字的属性或者方法( 方法隐藏只有一种形式,就是父类和子类存在相同的静态方法)时,父类的同名的属性或者方法形式上不见了,实际是还是存在的。
关于隐藏和覆盖的讨论见:Java中的隐藏和覆盖