Search code examples
javasubclasssuperclass

Proper way of calling a method in a subclass if it's referenced as a super class


class SuperClass () {
  doSuperStuff();
}

class SubClass extends SuperClass () {
  doStuff();
}

SuperClass aClass = new SubClass();

In order to call the method doStuff() do I need to cast it like (SubClass)aClass.doStuff(); ?

  1. Is that normally the way to do it?
  2. Is there a better way?
  3. Should I "always" initialize SubClass that way in case I want to put a bunch of subclasses of SuperClass into an array or something like that?

UPDATE: After reading everyone's response:

Ok. I'm definitely missing something in my understanding. I thought that having a subclass inherit everything from the superclass and then making one more method inside the subclass is ok. Should I be making an interface then?

Also, I had SuperClass class = new SubClass(); but renamed it to SuperClass aClass = new SubClass();


Solution

    • First of all, if you want to invoke a method from the subclass, in the first place you don't have to use a data type of superclass to create the variable. You could simply:

      MySubClass obj1 = new MySubClass();
      

    obj1 will be able to access both methods from its superclass (due to inheritance, except private methods in the superclass) and from itself.

    • Secondly, you can't name a variable as class.

    • Thirdly, if you want to do a casting, it goes like this:

      MySuperClass obj2 = new MySubClass();
      ((MySubClass)obj2).doStuff();