当前位置: 技术问答>java相关
SCJP多态题一
来源: 互联网 发布时间:2015-03-25
本文导语: 这道题我看注释可以看懂,但是发现多态的规则实在太多太乱,心里比较糊 想请各位高手详细解释一下 public class PrivateTest { public static void main(String s[]) { new P...
这道题我看注释可以看懂,但是发现多态的规则实在太多太乱,心里比较糊
想请各位高手详细解释一下
public class PrivateTest
{
public static void main(String s[])
{
new PTSuper().hi(); // Prints always Super
new PTSub().hi();
// Prints Super when subclass doesn't have hi method
// Prints Sub when subclass has hi method
PTSuper sup;
sup = new PTSub();
sup.hi();
// Prints Super when subclass doesn't have hi method
// Prints Sub when subclass has hi method
}
}
class PTSuper
{
public void hi()
{
// Super-class implementation always
// calls superclass hello
hello();
}
private void hello()
{
// This method is not inherited by subclasses,
// but exists in them.
// Commenting out both the methods in the subclass
// show this.
// The test will then print "hello-Super" for all three calls
// i.e. Always the super-class implementations are called
System.out.println("hello-Super");
}
}
class PTSub extends PTSuper
{
public void hi()
{
// This method overrides super-class hi,
// calls subclass hello
try
{
hello();
}
catch(Exception e) { }
}
void hello() throws Exception
{
// This method is independent from super-class hello
// Evident from, it's allowed to throw Exception
System.out.println("hello-Sub");
}
}
想请各位高手详细解释一下
public class PrivateTest
{
public static void main(String s[])
{
new PTSuper().hi(); // Prints always Super
new PTSub().hi();
// Prints Super when subclass doesn't have hi method
// Prints Sub when subclass has hi method
PTSuper sup;
sup = new PTSub();
sup.hi();
// Prints Super when subclass doesn't have hi method
// Prints Sub when subclass has hi method
}
}
class PTSuper
{
public void hi()
{
// Super-class implementation always
// calls superclass hello
hello();
}
private void hello()
{
// This method is not inherited by subclasses,
// but exists in them.
// Commenting out both the methods in the subclass
// show this.
// The test will then print "hello-Super" for all three calls
// i.e. Always the super-class implementations are called
System.out.println("hello-Super");
}
}
class PTSub extends PTSuper
{
public void hi()
{
// This method overrides super-class hi,
// calls subclass hello
try
{
hello();
}
catch(Exception e) { }
}
void hello() throws Exception
{
// This method is independent from super-class hello
// Evident from, it's allowed to throw Exception
System.out.println("hello-Sub");
}
}
|
《scjp认证套题解析》就在csdn的文档区,也可以看cherami的专区
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。