Hedayat Mahdipour
Hedayat Mahdipour

Reputation: 183

How to call subclass method through superclass instance in java?

Suppose we have a superclass such as

public class Superclass  
{  
    public void method1() {  
        // do something 
    }  
}// end Superclass

and a Subclass such as

public class Subclass extends Superclass
{
    public void method1() {
        //override method1() of Superclass
    }

    public void method2() {
        // bla bla bla
    }
}// end Subclass

Now consider the following code

public static void main( String[] args ) {
    Superclass obj = new Subclass();
}

I'm looking for a way to call method2() through variable obj. Is there any way to do this? If so, how can this task be done?

Upvotes: 1

Views: 3226

Answers (2)

Daniel Pryden
Daniel Pryden

Reputation: 60957

As the comment above points out, if you need to do this it may indicate that your classes are not modeled correctly.

Often a better approach would be to provide a default implementation in the supertype and simply have the subtype override the implementation.

For example:

public class Superclass {
  public void method1() {
    // method1 implementation
  }

  public void method2() {} // empty implementation
}

public class Subclass extends Superclass {
  @Override
  public void method2() {
    // do subclass stuff
  }
}

Then at your call site you would just need to do:

Superclass obj = new Subclass();
// Since the runtime type is Subclass, this calls Subclass's
// implementation of method2
obj.method2();

Upvotes: 3

Nir Levy
Nir Levy

Reputation: 12953

to do so, you have to cast it obj to SubClass:

((Subclass) obj).method2();

Upvotes: 2

Related Questions