当前位置: 技术问答>java相关
请高手回答这个问题,请注意看注释部分
来源: 互联网 发布时间:2015-10-05
本文导语: 抽象父类: package com.tomchen.study.javalan.inheritance; public abstract class Parent { public Parent() { System.out.println( "Parent constructor is invoked" ); } public abstract void abstractMethod(); public void callMethod(...
抽象父类:
package com.tomchen.study.javalan.inheritance;
public abstract class Parent
{
public Parent()
{
System.out.println( "Parent constructor is invoked" );
}
public abstract void abstractMethod();
public void callMethod()
{
abstractMethod(); //能不能调用到子类的实现????
}
public static void main(String[] args)
{
}
}
子类:
package com.tomchen.study.javalan.inheritance;
public class Son extends Parent
{
public Son()
{
}
public void abstractMethod()
{
System.out.println( "abstractMethod was implimented by son" );
}
}
package com.tomchen.study.javalan.inheritance;
public abstract class Parent
{
public Parent()
{
System.out.println( "Parent constructor is invoked" );
}
public abstract void abstractMethod();
public void callMethod()
{
abstractMethod(); //能不能调用到子类的实现????
}
public static void main(String[] args)
{
}
}
子类:
package com.tomchen.study.javalan.inheritance;
public class Son extends Parent
{
public Son()
{
}
public void abstractMethod()
{
System.out.println( "abstractMethod was implimented by son" );
}
}
|
可以的。
main里面这样写就行了
Parent p = new Son();
p.callMethod();
main里面这样写就行了
Parent p = new Son();
p.callMethod();
|
面向对象的多态性可以保证通过父类访问到相应的子类的方法
|
可以呀,
Son类等价于:
public class Son extends Parent
{
public Son()
{
System.out.println( "son constructor is invoked" );
}
public void abstractMethod()
{
System.out.println( "abstractMethod was implimented by son" );
}
public static void main(String[] args)
{
Parent p = new Son();
p.callMethod();
}
public void callMethod()
{
abstractMethod(); //能不能调用到子类的实现????
}
}
结果为:
Parent constructor is invoked
son constructor is invoked
abstractMethod was implimented by son
Son类等价于:
public class Son extends Parent
{
public Son()
{
System.out.println( "son constructor is invoked" );
}
public void abstractMethod()
{
System.out.println( "abstractMethod was implimented by son" );
}
public static void main(String[] args)
{
Parent p = new Son();
p.callMethod();
}
public void callMethod()
{
abstractMethod(); //能不能调用到子类的实现????
}
}
结果为:
Parent constructor is invoked
son constructor is invoked
abstractMethod was implimented by son