#this vs super

30 messages · Page 1 of 1 (latest)

latent plank
#

Can this and super() refer to the same thing?

severe templeBOT
#

This post has been reserved for your question.

Hey @latent plank! 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.

latent plank
#

A bit confused about them

coarse dagger
#

yes and no

gleaming gull
#

no

coarse dagger
#

this.<property of superclass> can technically be the same as super.<same property>, but it doesn't have to

latent plank
#

I don’t use super whej initializing fields in constructor right

#

When

gleaming gull
#

super() is quite distinct from super

latent plank
#

I use this

gleaming gull
#

do you mean super()/this() or super/this

#

ah the latter i suppose

coarse dagger
#

this refers to the current class' context, this() calls an empty constructor on the current context

latent plank
#

Ah

#

I think it makes sense

coarse dagger
#

same with super, super refers to the superclass' context, super() calls an empty constructor on the superclass context

latent plank
#

So if I have a stand-alone class

#

That isnt extended or anything

#

I use this

coarse dagger
#

what do you actually want to do

gleaming gull
#

this is the current instance, it holds all the stuff inherited by the superclass, except those overridden, as well as everything declared by the current class
super is the current instance referred to as if it were just the superclass, so doing super.field wouldn't work for fields declared in the current class
super could be used to reference methods that aren't overridden, but doing so makes it read as if it were overridden, which makes it hard to read; so the convention is to always use this unless you need super specifically

#

tl;dr, you could use super in place of this for some stuff, but you shouldn't. just use it for super constructors and overridden methods

gleaming gull
#

there will always be a superclass

#

regardless, you should just be using super for the super constructor and overridden methods, and for nothing else, for readability and maintainability

#

oh and overridden fields i guess, those are less common than the other 2 though

gleaming gull
latent plank
#

👍