给个例子给你参考一下,这是我自己学习的时候写的代码
/*
父类和子类都定义有相同的【静态变量】【静态方法】【成员变量】【成员方法】,
当 Father son = new Son();时,son调用变量和方法,到底是调用哪个呢?
*/
class Father
{
static int n = 10;
int c = 100;
public static void run()
{
System.out.println("staic father is funning");
}
public void go()
{
System.out.println("father is going");
}
}
class Sun extends Father
{
static int n = 20;
int c = 200;
public static void run()
{
System.out.println("staic sun is funning");
}
public void go()
{
System.out.println("sun is funning");
}
}
public class FS
{
public static void main(String args[])
{
Father sun = new Sun();
sun.run();//静态调用父类的
sun.go();//调用子类的
//不管是静态变量还是成员变量,都是调用父类的
//System.out.println("n="+Father.n);两者结果一样
System.out.println("n="+sun.n);
System.out.println("c="+sun.c);
//如果想调用Sun中的n,则使用
System.out.println("n="+Sun.n);
}
} |