大家请看书上的一个例子: 第一个类:
public class Planet
{
public static void hide()
{
System.out.println("The hide method in Planet.");
}
public void override()
{
System.out.println("The override method in Planet.");
}
}
第二个类是第一个的子类:
public class Earth extends Planet
{
public static void hide()
{
System.out.println("The hide method in Earth.");
}
public void override()
{
System.out.println("The override method in Earth.");
}
public static void main(String[] args)
{
Earth myEarth=new Earth();
Planet myPlanet=(Planet)myEarth;
myPlanet.hide();
myPlanet.override;
}
}
此程序的输出是; The hide method in Planet.
The override method in Earth.
大家看书上的解释:main方法创建了一个Earth实例,
将此实例转换为一个Planet引用,然后在此实例上调用hide和override方法。
被调用的隐藏方法是超类中的方法,而被调用的覆盖方法是子类中的方法。
下面两句话不怎么理解,各位指教:
对于类方法,运行时系统调用当前对象引用的编译时类型中定义的方法;
对于实例方法,运行时系统调用当前对象引用的运行时类型中定义的方法。
也就是编译时类型与运行时类型在这里怎么理解??
望各位能够指点!!!!
public class Planet
{
public static void hide()
{
System.out.println("The hide method in Planet.");
}
public void override()
{
System.out.println("The override method in Planet.");
}
}
第二个类是第一个的子类:
public class Earth extends Planet
{
public static void hide()
{
System.out.println("The hide method in Earth.");
}
public void override()
{
System.out.println("The override method in Earth.");
}
public static void main(String[] args)
{
Earth myEarth=new Earth();
Planet myPlanet=(Planet)myEarth;
myPlanet.hide();
myPlanet.override;
}
}
此程序的输出是; The hide method in Planet.
The override method in Earth.
大家看书上的解释:main方法创建了一个Earth实例,
将此实例转换为一个Planet引用,然后在此实例上调用hide和override方法。
被调用的隐藏方法是超类中的方法,而被调用的覆盖方法是子类中的方法。
下面两句话不怎么理解,各位指教:
对于类方法,运行时系统调用当前对象引用的编译时类型中定义的方法;
对于实例方法,运行时系统调用当前对象引用的运行时类型中定义的方法。
也就是编译时类型与运行时类型在这里怎么理解??
望各位能够指点!!!!
static void p(){
System.out.println("static sup");
}
void print(){
System.out.println("sup");
}
}class sub extends sup{
static void p(){
System.out.println("static sub");
}
void print(){
System.out.println("sub");
}
}class TestA{
public static void main(String[] arg){
sup s=new sub();
s.p(); //static sup
s.print(); //sub
}
}----------------------
事例方法被覆盖,静态方法被隐藏,