我有一个关于如何从子类或父类定义方法的问题。例如:
public class Thought
{
//-----------------------------------------------------------------
// Prints a message.
//-----------------------------------------------------------------
public void message()
{
System.out.println ("I feel like I'm diagonally parked in a " +
"parallel universe.");
System.out.println();
}
}
子类是:
public class Advice extends Thought
{
//-----------------------------------------------------------------
// Prints a message. This method overrides the parent's version.
//-----------------------------------------------------------------
public void message()
{
System.out.println ("Warning: Dates in calendar are closer " +
"than they appear.");
System.out.println();
super.message(); // explicitly invokes the parent's version
}
}
如果我想从主方法调用方法消息,我是否必须使用 Thought.message
或 Advice.message
因为我使用了 super 调用程序。 super.(method)() 从技术上讲是否只是将父方法复制并粘贴到子方法中,从而允许您仅创建子方法的对象?
最佳答案
这完全取决于您如何初始化对象。您可以同时使用两者。但是使用多态性你可以做这样的事情:
Thought t = new Advice();
t.message();
并且没有多态性:
Advice a = new Advice();
a.message();
由于 Advice
继承了 Thought
方法 message()
并实际调用了对其父类(super class)的调用,因此这两个方法这两个示例都会被调用。
关于java - 多态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35570040/