我有一个关于如何从子类或父类定义方法的问题。例如:
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.( method )()只是将父方法复制并粘贴到子方法中,允许您只创建子方法的对象吗?
发布于 2016-02-23 06:08:34
这都取决于您如何初始化对象。你可以两者兼用。但是使用多态性,您可以这样做:
Thought t = new Advice();
t.message();没有多态性:
Advice a = new Advice();
a.message();因为是Advice从Thought继承了message()方法,并且实际上调用了它的超类,所以这两个方法都将在两个示例中调用。
发布于 2016-02-23 06:08:26
我觉得你应该回去多学点.
是的,您可以只创建子对象,但它仍然是父对象的isA实例。
super.method()调用超类方法。它不会将超类方法复制到子类中。
方法的超类实现可能使用私有变量,因为子类无法访问。
发布于 2016-02-23 06:16:14
Thought t1 = new Thought();
t1.message(); // invokes Thought#message()
Thought t2 = new Advice();
t2.message(); // invokes Advice#message()
Advice a1 = new Advice();
a1.message(); // invokes Advice#message()
Advice a1 = new Thought(); //COMPILATION ERROR在调用实例方法时,将在运行时执行引用中的任何对象。
https://stackoverflow.com/questions/35570040
复制相似问题