#Weird behaviour with class members

30 messages · Page 1 of 1 (latest)

proven cape
#

So there is this task we are supposed to complete in order to learn how static and dynamic binding works, see the attached image for the code and classes.
C is a subclass of B, and B is a subclass of A.

Line System.out.println(p1.x); prints 1, which is the x defined for Print1 class.
In line p1.print(c); it would be logical to execute method print(B b) from Print1 class, which is also what the IntelliSense suggests is happening.
However actually, it is running the print(B b) method from Print2 class with the x = 3 from Print2.

How is this possible? It seems entirely random to me, especially since it previously used x = 1 from Print1, and it also does not use print(C c) from Print2 while the parameter is a C class.

tall violetBOT
#

This post has been reserved for your question.

Hey @proven cape! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

tough dock
#

that's what would make sense

proven cape
#

no, its printing 4

#

which is SO WEIRD if you ask me

#

I looked at it with the debugger, it goes through the second print method of the Print2 class with x = 3

tough dock
#

so first 3, then 4, right?

proven cape
#

thats what makes it weird, first it prints 1

#

then 4

naive widget
#

can you show the declarations for A,B,C

proven cape
naive widget
#

oh, im dumb lmao

#

let me reread one sec

#

ah

naive widget
proven cape
#

yes

naive widget
#

oh i misread that again

#

im just confusing myself now lol

#

ok no

#

since p1 is of type Print1, it looks for the method print(<super C>), which ends up being print(B b)
that's overridden by Print2, the actual object

#

print(C) is not overriding anything/isn't present in the superclass so you can't access it from the superclass type

#

so it calls Print2.print(B b)

proven cape
#

ok and then it prints 1 instead of 3 because x in Print2 does not interact with the x of Print1

#

right?

naive widget
#

yes

proven cape
#

ok oml that confused me so much

#

thank you

tall violetBOT
# proven cape thank you

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.