5th Nov 2022, 4:38 AM
♡GDY♡
♡GDY♡ - avatar
4 Answers
+ 3
This is exactly why I say this example code is garbage. It's just meaningless and too abstract, so your question "why" is perfectly valid. I guess the only reason to write it this way, is to explain how polymorphism works. When you have void m1(A a) This means that the input parameter of this function is an object of type A. But when the function is actually called, in line 10 of your code, we are passing an instance of B to it. But this is still OK, because B is a subclass of A. That's polymorphism for you.
5th Nov 2022, 8:30 AM
Tibor Santa
Tibor Santa - avatar
+ 7
When you call this method: c.m1(new B()); Look at what happens in the m1 method of class C: void m1(B b) { System.out.println("Two"); super.m1(new B()); } First, Two is printed. Then the m1 method of the superclass is invoked. Because C inherits from B, the m1 method of B prints One. Inheritance can be quite complex topic already, and I find these dummy examples even more confusing for beginners. Anyway, asking for "Help" and not explaining what is giving you trouble, is really an incomplete question... Just write which part is not clear for you if you need more explanation.
5th Nov 2022, 5:31 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Thank you so much for the help
5th Nov 2022, 6:09 AM
♡GDY♡
♡GDY♡ - avatar
+ 2
But why here we you m1(A a) and m1(B b) is that objects of the class
5th Nov 2022, 6:25 AM
♡GDY♡
♡GDY♡ - avatar