在继承机制中,类的静态方法只能被子类的静态方法覆盖,且覆盖以后没有多态(访问的是父类的静态方法);
示例程序:
class StaticTest1
{
private static int c=2017;
public static void print(){
System.out.println(c+" is a different year!");
}
}
public class Statictest extends StaticTest1
{
private static int c=2018;
public static void print(){
System.out.println(c+" will be a good year!");
}
public static void main(String[] args)
{
StaticTest1 s=new Statictest();
s.print();
}
}
/*Output:
2017 is a different year!
*/
若print()方法为非静态方法, 输出的肯定是:“2018 will be a good year!”了。
在下面的程序中将会出现错误:
class StaticTest1
{
private static int c=2017;
/*public static void print(){
System.out.println(c+" is a different year!");
}*/
}
public class Statictest extends StaticTest1
{
private static int c=2018;
public static void print(){
System.out.println(c+" will be a good year!");
}
public static void main(String[] args)
{
StaticTest1 s=new Statictest();
s.print();
}
}
错误提示是:s.print()
找不到符号。