How does method overriding work?

╄→гoц情女王★ 提交于 2019-12-13 08:08:39

问题


Look at the following code snippet:

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");
   }
}

in main method:

A a=new B();
a.fun1()

The output is:

fun1 of A
fun2 of B

Can you please explain this output.

According to me a.fun1 is calling fun1 of A since fun1 is not overriden by B(otherwise it would have called fun1 of B). And, fun2() in fun1 of A is calling fun2 of B since fun2 is overriden and object of B is created at runtime. Am I thinking in correct direction ?


回答1:


It has been answered but I'm putting this as an answer anyway because I object to the simplification of the example code and I can't properly express that in a comment. Using names such as A and B and fun() really does not help anyone understand anything, including yourself. Try this:

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?
    }

}

If you use something "realistic" that is easy to envision, it all of a sudden becomes almost self-explanatory.

Note: I purposely left out any reference to the abstract keyword because that is not within the context of this question.




回答2:


Your understanding is mostly correct. Just remember that all functions in Java are virtual and methods will be called depending on run-time type of the object you're working with. The trick is that when you do fun2(); there is an implicit this so it becomes this.fun2(). Since this in your exapmle this points to an object of class B, the overriden method will be called.




回答3:


Yes. Not much more to say than that your interpretation is correct.




回答4:


A a=new B();

That line says that get the implementations in the type B when they called. Keep it simple. You are right.



来源:https://stackoverflow.com/questions/24556202/how-does-method-overriding-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!