[英]How does (this) overriding tostring method for LinkedList class work?
[英]How does method overriding work?
查看以下代碼片段:
class A
{
void fun1()
{
System.out.println("fun1 of A");
fun2();
}
void fun2()
{
System.out.println("fun2 of A");
}
}
class B extends A
{
void fun2()
{
System.out.println("fun2 of B");
}
}
在主要方法中:
A a=new B();
a.fun1()
輸出為:
fun1 of A
fun2 of B
能否請您解釋一下此輸出。
根據我的說法, a.fun1
正在調用A
fun1
,因為fun1
沒有被B
覆蓋(否則它將調用B
fun1
)。 而且, A
fun1
的fun2()
調用了B
fun2
,因為fun2
被覆蓋並且B的對象在運行時創建。 我在想正確的方向嗎?
它已經得到了回答,但是無論如何我都將其作為答案,因為我反對簡化示例代碼,並且無法在注釋中正確表達出來。 使用諸如A,B和fun()之類的名稱實際上並不能幫助任何人理解任何東西,包括您自己。 嘗試這個:
class Animal {
public void makeSound(){
System.out.println("<silence>");
}
}
class Cow extends Animal {
public void makeSound(){
System.out.println("Moooooooo");
}
}
public class Test {
public static void main(String[] args){
Animal animal = new Cow();
animal.makeSound(); // what sound is the animal going to make?
}
}
如果您使用容易想到的“現實”東西,突然之間幾乎可以不言自明。
注意:我故意省略了對abstract關鍵字的任何引用,因為這不在此問題的上下文內。
您的理解基本上是正確的。 只需記住,Java中的所有函數都是虛函數,並且將根據所使用對象的運行時類型來調用方法。 訣竅是當您執行fun2();
存在一個隱式this
因此它變成this.fun2()
。 由於這在您的exapmle this
點類的對象B
,則覆蓋方法將被調用。
是。 只能說您的解釋是正確的。
A a=new B();
該行說在調用時以B
類型獲得實現。 把事情簡單化。 你是對的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.