raff5184
raff5184

Reputation: 382

java how to get superclass reference in subclass

I have 3 classes:

class Superclass...

public class Generic{
     public Generic(Superclass s){...}
}

And a subclass extending Superclass

class SubClass extends Superclass{
      public void methodM(){
           Generic g = new Generic(???);
           ...
      }
}

In methodM I use the constructor Generic and I want to pass a reference to the Superclass instance extended by Subclass. So I don't want to do something like new Generic(new Superclass), rather something like: new Generic(super.IdontKnowWhat)

thank you

Upvotes: 0

Views: 2252

Answers (3)

U can pass the reference of the subclass as it extends the superclass.. But it depends on what methods u want to acssess..If u pass reference of subclass then u should acssess the methods of subclass through the object received in constructor of Generic class.. So u should construct the new object of superclass in case u want to acssess methods of superclass..

Upvotes: 0

anirudh
anirudh

Reputation: 4176

Just call it as super.parameter as super is an inbuilt keyword used to reference the super class fields. You can read about super in the java docs tutorial for super.

Upvotes: 1

Evan Knowles
Evan Knowles

Reputation: 7501

The reference to the current object is implicitly a reference to a superclass as well (as it extends it).

So you should be able to do

 Generic g = new Generic(this);

Upvotes: 1

Related Questions